Querying Arrays

db.inventory.insertMany( [
   { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);

Matching Nested Array Documents

db.inventory.find(
  { "instock":
    { warehouse: "A", qty: 5 }
  }
)
// Matching document
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] }

Querying Conditions on Nested Arrays 1

db.inventory.find( { 'instock.qty': 5 } )
db.inventory.find(
  { 'instock.qty':
    { $lte: 20 }
  }
)

Querying Conditions on Nested Arrays 2

db.inventory.find(
  { 'instock.qty':
    { $lte: 20, $gte: 5 }
  }
)
db.inventory.find(
  { 'instock.qty':
    { $lte: 20 },
    'instock.qty': { $gte: 5}
  }
)

Querying Array Documents at Index

db.inventory.find(
  { 'instock.0.qty':
    { $lte: 20 }
  }
)

Liberal Matching Without $elemMatch

db.inventory.find(
  {
    "instock.qty": 5,
    "instock.warehouse": "A"
  }
)

Querying with Many Conditions on Arrays

db.inventory.find(
  { "instock":
    { $elemMatch:
      {
        qty: 5,
        warehouse: "A"
      }
    }
  }
)

Querying with Range Conditions on Arrays

db.inventory.find(
  { "instock":
    { $elemMatch:
      {
        qty: { $gte: 5 },
        warehouse: "A"
      }
    }
  }
)

Querying with Many Range Conditions on Arrays

db.inventory.find(
  { "instock":
    {
      $elemMatch: {
        qty: {
          $gte: 5,
          $lte: 20
        },
        warehouse: "A"
      }
    }
  }
)

 Previous Lesson Next Lesson 

Outline

[menu]

/