Logical Operators

Logical operators allow you to combine multiple query conditions to filter documents.

1. $or

Matches documents where at least one of the conditions is true.

db.users.find({
  $or: [
    { status: "A" },
    { age: { $lt: 30 } }
  ]
})

2. $and

Matches documents where all specified conditions are true. Note that MongoDB often performs an implicit `$and` when you provide multiple fields in a query.

// Explicit $and
db.users.find({
  $and: [
    { status: "A" },
    { age: { $gt: 25 } }
  ]
})

// Implicit $and (Same result)
db.users.find({ status: "A", age: { $gt: 25 } })

3. $not

Inverts the effect of a query expression and returns documents that do not match the query expression.

// Find documents where age is NOT greater than 25
db.users.find({
  age: { $not: { $gt: 25 } }
})

4. $nor

Matches documents that fail all query conditions (The opposite of `$or`).

db.users.find({
  $nor: [
    { price: 1.99 },
    { sale: true }
  ]
})
Usage Tip: Use `$and` explicitly only when you need to use the same operator or field multiple times in a single query (e.g., multiple `$or` clauses).