Skip to content

Querying & Filtering

Logical Operators

$and, $or, $nor and $not — when implicit AND is enough, and when you must be explicit.

IntermediateAbout 5 minutes

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"] } })
Different fields, either may match

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 } }
  ]
})
$or across fields. $and when you must group.

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 wraps an operator, not a whole document

$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?

Think about it first.

Interview question

When do you actually need $and?

Think about it first.

Practice

Implicit AND — two fields, no $and required.