Querying & Filtering
Logical Operators
$and, $or, $nor and $not — when implicit AND is enough, and when you must be explicit.
Sibling keys are already AND. You write $and / $or / $nor / $not when that shorthand cannot say what you mean — or when you want the grouping obvious.
db.users.find({
$or: [
{ city: "Bangalore" },
{ city: "Pune" }
]
})
// same thing — one field, $in
db.users.find({ city: { $in: ["Bangalore", "Pune"] } })Prefer $in when it is the same field. Use $or when the branches are different: 'Bangalore developers or anyone with role: "admin"'.
db.users.find({
$or: [
{ city: "Bangalore", role: "developer" },
{ role: "admin" }
]
})
db.orders.find({
$and: [
{ status: { $ne: "cancelled" } },
{ amount: { $gte: 4500 } }
]
})The second $and is optional — those two keys could be siblings. You need $and when JSON cannot hold two keys with the same name, or when you wrap several $or groups. $nor is 'none of these branches match'. $not negates an operator expression on a field.
db.users.find({ age: { $not: { $gt: 25 } } })$not: { $gt: 25 } matches age ≤ 25 and documents with no age. That surprise is why people prefer $lte: 25 when the field is always present.
Interview question
When would you use $in rather than $or?
$in when one field may be any of several values. $or when branches involve different fields or a mix of conditions. $in is easier to read and usually easier on the planner.
Interview question
When do you actually need $and?
When sibling keys cannot express it — two operators that cannot share one field object, or grouping several $or clauses. Ordinary { city: "Bangalore", isActive: true } already means AND.
Practice
Implicit AND — two fields, no $and required.