← Back to MongoDB Course | Chapter 6: Query Operators | Lesson 2 of 7

Logical operators ($and $or $not $nor)

Logical operators combine several conditions into one query.
Syntax
javascript
{ $and: [condition1, condition2] }
{ $or: [condition1, condition2] }
{ field: { $not: { $gt: value } } }
{ $nor: [condition1, condition2] }

Logical operators ($and $or $not $nor)

$and requires all conditions, $or requires at least one, $nor requires none, and $not inverts a single operator expression.

Top-level conditions are ANDed implicitly, so $and is needed mainly when the same field appears twice. Put the most selective conditions first only for readability; the planner reorders.

Note: $or clauses can use different indexes, so index each branch.

Example: Logical operators ($and $or $not $nor)

bash
test> db.users.insertMany([
...   { _id: 1, name: "Ada", age: 36, city: "London" }, { _id: 2, name: "Bob", age: 25, city: "Oslo" },
...   { _id: 3, name: "Cy", age: 41, city: "Oslo" }
... ])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
test> db.users.find({ $or: [{ city: "London" }, { age: { $gt: 40 } }] }, { name: 1, _id: 0 })
[ { name: 'Ada' }, { name: 'Cy' } ]
test> db.users.find({ $and: [{ age: { $gt: 20 } }, { age: { $lt: 40 } }] }, { name: 1, _id: 0 })
[ { name: 'Ada' }, { name: 'Bob' } ]
test> db.users.find({ age: { $not: { $gt: 30 } } }, { name: 1, _id: 0 })
[ { name: 'Bob' } ]
test> db.users.find({ $nor: [{ city: "Oslo" }, { age: { $lt: 30 } }] }, { name: 1, _id: 0 })
[ { name: 'Ada' } ]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Repeating a key in one object and losing one condition
  2. Using $not on a plain value
  3. Forgetting $or needs an array
Chapter Summary
  • $and all, $or any, $nor none
  • $not negates an operator expression
  • Top-level fields are ANDed
  • $or needs an array of conditions
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.