querydrill

Learn ›MongoDB fundamentals ›Query operators

Logical operators and implicit AND

find()logical$and$gte$lt$or

Listing two fields in one filter is already an AND, so $and is rarely needed. $or is the one you actually have to write - and the one people get wrong when they need “this, and also either of those”.

$and

Usually implicit.

db.users.find({
  age: { $gte: 25 },
  status: "active"
})

Means:

age >= 25
AND
status = active

Explicit:

db.users.find({
  $and: [
    { age: { $gte: 25 } },
    { status: "active" }
  ]
})

Usually you don’t need $and.

$or

db.users.find({
  $or: [
    { status: "active" },
    { role: "admin" }
  ]
})

Important interview-style example

db.users.find({
  status: "active",
  $or: [
    { age: { $lt: 25 } },
    { role: "admin" }
  ]
})

Meaning:

status = active

AND

(
  age < 25
  OR
  role = admin
)

Practise this

1 exercise