$and and $or — MongoDB Technical Interview Questions & Answers

Combining multiple query conditions.

$and and $or

  • Simple meaning: $and requires every condition. $or requires at least one.
  • How to use: implicit AND is just { city: "Pune", marks: { $gt: 40 } }. Use $and when two checks hit the same field. $or: db.students.find({ $or: [{ city: "Pune" }, { marks: { $gt: 90 } }] }).
  • Try this: one student who is Pune OR high marks.
  • Common mistake: putting $or next to a field like { city: { $or: ... } }. $or is a top-level array of filters.
  • Interview tip: {a:1, b:2} is AND. $or needs an array of documents.

Technical Interview Tip: Implicit AND vs $or array.

Code Examples for $and and $or

$and and $or — working example

db.users.find({
  $and: [
    { city: "Pune" },
    { $or: [{ role: "admin" }, { age: { $gte: 21 } }] }
  ]
})

$and and $or — $and / $or combine filter clauses; commas in one object are an implicit AND.

How to Explain $and and $or to an Interviewer

How do you OR two filters?

{ $or: [ { city: "Pune" }, { marks: { $gt: 90 } } ] }