Skip to content

Querying & Filtering

Combining Query Conditions

Realistic filters that mix comparison, logic and nested fields without becoming unreadable.

IntermediateAbout 6 minutes

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 }
})
Delivered (or completed) orders of at least ₹4500, not cancelled — say it, then write it
{ userId: ObjectId("64a1…0001"), amount: 4500, status: "completed" }
db.users.find({
  $or: [
    { city: "Bangalore", role: "developer", isActive: true },
    { role: "admin" }
  ]
})
Active Bangalore developers, or any admin — $or because the shapes differ

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 }
})
Embedded specs.wireless — still equality, still AND with price

How to keep it readable

  • Sibling keys for AND. $in for one field, many values. $or only when branches disagree.
  • Range bounds on one field object: { amount: { $gte: 4500, $lt: 100000 } }, not two $and clauses.
  • 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?

Think about it first.

Practice

Two fields, implicit AND — the combined-filter shape you will write constantly.