How to Query MongoDB Documents
- The queries below assume the following documents have been inserted
db.inventory.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" }
]);
Finding SOME documents in a Collection
- Simple conditions can be added like below:
db.inventory.find( { status: "D" } )
- Multple conditions imply an AND between the constraints
db.inventory.find( { status: "D", item: "planner" } )
Finding SOME documents using OR
- Can be used with the same properties
db.inventory.find(
{ $or: [
{ type: "Planner" },
{ type: "Notebook" }
]
}
)
- Can be used with the different properties
db.inventory.find(
{ $or: [
{ status: "A" },
{ type: "Notebook" }
]
}
)
Finding SOME documents using RANGES
- Simple ranges have the general form syntax of the below template:
db.collection.find( { <field>: { $gt: <value1>, $lt: <value2> } } );
- Multple conditions imply an AND between the constraints
db.inventory.find( { status: "A", qty: { $lt: 30 } } )
Querying for properties IN a set
db.inventory.find( { status: { $in: ["A", "B", "C"] } } )
db.inventory.find( { type: { $in: ["Journal", "Notebook", "Paper"] } } )
Querying Nested Documents
- Matches can be made using exact nested fields like below:
db.inventory.find({ status: "A", size: { h: 14, w: 21, uom: "cm" } })
- Matches can also be made using more relaxed nested conditions:
db.inventory.find({ "size.h": 14 });
- OR using a combination of an EXACT property and a relaxed nested condition
db.inventory.find({ status: "A", "size.h": 14 })
Range Queries in Nested Documents
- Reminder of document shape and properties
{
"_id" : ObjectId("5b631aff2f6ff13721a2e38b"),
"item" : "journal",
"status" : "A",
"size" : {
"h" : 14,
"w" : 21,
"uom" : "cm"
}
}
- Single Range in a nested document
db.inventory.find({ "size.h": { $gt: 10 } })
- Multiple ranges in a nested document
db.inventory.find({ "size.h": { $gt: 10, $lt: 100 } })
Range Queries in Nested Documents using OR
db.inventory.find( {
status: "A",
$or: [
{ qty: { $lt: 30 } },
{ "size.h": { $gt: 10 } }
]
}
)