Skip to the workspace
Pebellslearn by building
Query Operators  ›  Lesson

Logical Operators: $and, $or, $nor, $not

$or 12 minFilters are ANDed by default, $or matches if any listed condition holds, $nor matches if none do, $not negates one field's condition, and explicit $and is needed only when the same key must appear twice.

mongodb / Logical Operators: $and, $or, $nor, $not

Explore each scene at your own pace.

01 · The rule

The rule

Logical Operators: $and, $or, $nor, $not

"Cheap or out of stock", "neither sci-fi nor running low", "price not above 8". Once questions combine conditions with or, nor and not, you need MongoDB's logical operators. The good news: you already use AND without writing it.

The rule

Commas already AND; $or any, $nor none, $not flips one field.

_id title year price stock genres
1 Dune 1965 9.99 12 sci-fi, classic
2 Neuromancer 1984 8.5 0 sci-fi, cyberpunk
3 Emma 1815 4.25 7 classic, romance
4 The Hobbit 1937 7.99 3 fantasy, classic, adventure
5 Circe 2018 12 5 fantasy, myth
db.books.find({ $or: [ { price: { $lt: 5 } }, { stock: 0 } ] })          // Emma, Neuromancer
db.books.find({ $nor: [ { genres: "sci-fi" }, { stock: { $lt: 5 } } ] }) // Emma, Circe
db.books.find({ price: { $not: { $gt: 8 } } })                           // Emma, The Hobbit
  • Implicit AND: { genres: "classic", stock: { $gt: 5 } } needs both.
  • $or takes an array of condition documents; a document matches if any holds.
  • $nor takes an array; a document matches if none holds, and like $ne, missing fields count as "does not hold".
  • $not is different: it sits inside a field and negates that field's operator. { price: { $not: { $gt: 8 } } } means "price is not above 8", which also includes documents with no price.
  • Explicit $and is needed when the same key must appear twice, most often two separate $or groups:
db.books.find({ $and: [
  { $or: [ { genres: "sci-fi" }, { genres: "fantasy" } ] },
  { $or: [ { stock: 0 }, { price: { $gt: 10 } } ] }
] })                                                                        // Neuromancer, Circe
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.