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 } ] }
]);
db.inventory.find(
{ "instock":
{ warehouse: "A", qty: 5 }
}
)
// Matching document
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] }
db.inventory.find( { 'instock.qty': 5 } )
db.inventory.find(
{ 'instock.qty':
{ $lte: 20 }
}
)
db.inventory.find(
{ 'instock.qty':
{ $lte: 20, $gte: 5 }
}
)
db.inventory.find(
{ 'instock.qty':
{ $lte: 20 },
'instock.qty': { $gte: 5}
}
)
'<property>.<index>.<subProperty>'
db.inventory.find(
{ 'instock.0.qty':
{ $lte: 20 }
}
)
$elemMatch
the semantics mean: "If ANY COMBINATION of these conditions are met, then match"db.inventory.find(
{
"instock.qty": 5,
"instock.warehouse": "A"
}
)
$elemMatch
matches any document with a sub-document that satisfies the full querydb.inventory.find(
{ "instock":
{ $elemMatch:
{
qty: 5,
warehouse: "A"
}
}
}
)
$elemMatch
can be used with range conditionsdb.inventory.find(
{ "instock":
{ $elemMatch:
{
qty: { $gte: 5 },
warehouse: "A"
}
}
}
)
$elemMatch
can also be used with multiple range conditionsdb.inventory.find(
{ "instock":
{
$elemMatch: {
qty: {
$gte: 5,
$lte: 20
},
warehouse: "A"
}
}
}
)
/