Querying Arrays

This lesson makes the following assumptions:

1. You have properly connected to your database, and declared the following:

const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017"
const client = new MongoClient(uri, { useUnifiedTopology: true })

async function runQuery() {
    await client.connect()
    const database = client.db('test')
    const collection = database.collection('inventory')

     // insert query here
    const results =  


    await results.forEach(doc => console.log(doc))
    // close connection
    await client.close()

}
runQuery()

2. You have added the following test-data:

await collection.insertMany([
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);

Here is the document we will be querying for (in a variety of ways)

// Matching document
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] }

Querying Conditions on Nested Arrays 1

const results = await collection.find( { 'instock.qty': 5 } )
const results = await collection.find(
  { 'instock.qty':
    { $lte: 20 }
  }
)

Querying Conditions on Nested Arrays 2

const results = await collection.find(
  { 'instock.qty':
    { $lte: 20, $gte: 5 }
  }
)
const results = await collection.find(
  { 'instock.qty':
    { $lte: 20 },
    'instock.qty': { $gte: 5}
  }
)

Querying Array Documents at Index

const results = await collection.find(
  { 'instock.0.qty':
    { $lte: 20 }
  }
)

Liberal Matching Without $elemMatch

const results = await collection.find(
  {
    "instock.qty": 5,
    "instock.warehouse": "A"
  }
)

Querying with Many Conditions on Arrays

const results = await collection.find(
  { "instock":
    { $elemMatch:
      {
        qty: 5,
        warehouse: "A"
      }
    }
  }
)

Querying with Range Conditions on Arrays

const results = await collection.find(
  { "instock":
    { $elemMatch:
      {
        qty: { $gte: 5 },
        warehouse: "A"
      }
    }
  }
)

Querying with Many Range Conditions on Arrays

const results = await collection.find(
  { "instock":
    {
      $elemMatch: {
        qty: {
          $gte: 5,
          $lte: 20
        },
        warehouse: "A"
      }
    }
  }
)

 Previous Next 

Outline

[menu]

/