Querying & Filtering
Combining Query Conditions
Realistic filters that mix comparison, logic and nested fields without becoming unreadable.
Real filters stack what you just learned. The goal is a query you can say in a sentence, not a tree of $and you cannot read in review.
db.orders.find({
status: { $in: ["completed", "delivered"] },
amount: { $gte: 4500 }
}){ userId: ObjectId("64a1…0001"), amount: 4500, status: "completed" }db.users.find({
$or: [
{ city: "Bangalore", role: "developer", isActive: true },
{ role: "admin" }
]
})Dot notation for a nested field is the same filter rules on a path. Full treatment is the next module. One line so a combined query is not a mystery:
db.products.find({
"specs.wireless": false,
price: { $lte: 5000 }
})How to keep it readable
- Sibling keys for AND.
$infor one field, many values.$oronly when branches disagree. - Range bounds on one field object:
{ amount: { $gte: 4500, $lt: 100000 } }, not two$andclauses. - If you cannot read the filter out loud, split it or drop a redundant
$and. - Empty
$or: []is invalid. A branch that is{}matches everything — a hole in the logic.
Interview question
How would you write a filter for high-value completed orders from a given user?
Sibling keys: userId, status in the completed-like values or $eq, amount $gte a threshold. I would not wrap that in $and. If status can be completed or delivered, that is $in on status, still AND with the rest.
Practice
Two fields, implicit AND — the combined-filter shape you will write constantly.