Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 70 ยท Query operators

Logical Operators

Combine MongoDB conditions with implicit AND, $and, $or, $nor and $not. Learn the duplicate-key trap, how $not treats missing fields and how to nest filters.

A filter with one condition is easy. Real questions have several: "fantasy books under $10 that are in stock", "anything cheap or very long", "everything except the out-of-stock titles". MongoDB gives you a small set of logical operators to combine conditions: an implicit AND, plus $and, $or, $nor and $not. Together they can express any boolean condition.

This lesson uses the comparison operators from Comparison Operators, so skim that one first if $gt or $in look unfamiliar. The shell commands you see in plain code blocks are real mongosh syntax and cannot run on this site, because there is no MongoDB server here. Every runnable example uses the site's own practice engine, a small matcher written in JavaScript that implements these operators over an array of documents. The engine is a stand-in: it follows MongoDB's rules for the operators in this lesson, but it has no indexes, no query planner and none of MongoDB's performance behavior.

Implicit AND: several fields in one filter

When you put several fields in one filter document, MongoDB requires all of them to match. You do not write $and for this:

JavaScript
db.books.find({ genre: "fantasy", inStock: true, price: { $lt: 10 } })

That reads as "genre is fantasy AND inStock is true AND price is below 10". The same goes for several operators on one field: { price: { $gt: 10, $lt: 20 } } means greater than 10 and less than 20. Most of your queries will be plain implicit ANDs, and that is the form to prefer. It is short, and the query planner handles it well, for example by combining the bounds of a range on one indexed field.

Five ways to combine conditions

Implicit AND Many fields in one filter. All must match.
$and A list of filters. All must match.
$or A list of filters. At least one matches.
$nor A list of filters. None may match.

Arrays hold complete filters, so you choose the grouping.

1 / 2

The duplicate-key trap

Your filter is an ordinary object in your programming language, and an object cannot hold the same key twice. If you write $or twice, or the same field twice, the later one silently replaces the earlier one before MongoDB ever sees the filter. The first TryIt shows this with real data, and shows the fix with $and.

JS Implicit AND, and the duplicate-key trap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "broken" filter keeps only the second $or, so it returns every cheap or long book regardless of genre, including "Paper Kingdoms", a history title. The fixed version wraps the two $or clauses in an $and array. Arrays can hold any number of entries, and each entry is its own object, so there is no key to collide. This is the main reason $and exists: you need it when two conditions would otherwise need the same key in one object.

$or and $nor

$or takes an array of filters and matches a document when at least one of them matches. $nor is the opposite: it matches when none of them match.

JavaScript
// cheap OR very long
db.books.find({ $or: [{ price: { $lt: 10 } }, { pages: { $gt: 600 } }] })

// neither fantasy nor out of stock
db.books.find({ $nor: [{ genre: "fantasy" }, { inStock: false }] })

Two practical notes on $or. First, if all the branches test the same field with equality, $in is shorter and clearer: { genre: { $in: ["fantasy", "scifi"] } }. Second, when you use $or with indexes, MongoDB can use an index for each branch, but only if every branch has a usable index. One unindexed branch forces a full collection scan for the whole query. You will see how to check this in explain() and the Profiler.

$nor also matches documents where the mentioned fields do not exist at all, because "does not match" includes "cannot match". Keep that in mind with messy data.

$not: negating one field's condition

$not is different from the other three. It sits inside a field, wraps an operator expression and inverts it:

JavaScript
db.books.find({ price: { $not: { $gt: 20 } } })

A document matches when its price is not greater than 20. $not also accepts a regular expression literal, as in { title: { $not: /^The/ } }. It cannot take a plain value, so you cannot write { price: { $not: 20 } }; use $ne for that.

The surprise is that $not also matches documents where the field is missing. "Not greater than 20" is true when there is no price at all. The next TryIt makes the difference visible.

JS $or, $nor and the $not surprise

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare the last three lines. $lte: 20 skips the draft, because it has no price to compare. $not: { $gt: 20 } includes it. If you want "has a price and the price is at most 20", say so directly with $lte, or add $exists: true as the last line does. When a filter feels like a double negative, rewrite it with the positive operator.

Nesting: spelling out precedence

SQL has precedence rules (AND binds tighter than OR), and forgetting them is a classic bug. MongoDB has none, because you write the tree yourself. Every $and and $or holds an array of complete filters, and nesting decides the grouping. To express "(fantasy and under $10) or (scifi and in stock)":

JavaScript
db.books.find({
  $or: [
    { genre: "fantasy", price: { $lt: 10 } },
    { genre: "scifi", inStock: true }
  ]
})

Each array entry is an implicit AND, and the array as a whole is an OR. If you would rather have "fantasy and (under $10 or in stock)", you move the $or inside:

JavaScript
db.books.find({
  genre: "fantasy",
  $or: [{ price: { $lt: 10 } }, { inStock: true }]
})

Here the genre condition sits next to $or in the same object, so it is ANDed with the whole $or. The mistakes to watch for are not precedence but placement: a condition in the wrong array, or two $or keys in one object.

JS Two groupings, two answers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Habits that keep filters readable

  • Prefer the implicit AND and $in over $and and $or where they say the same thing.
  • Build filters from small pieces in code (const inStock = { inStock: true }) and combine them, which makes the structure easy to see and test.
  • Treat $not, $nor, $ne and $nin as "also matches missing fields" and add $exists: true when you need the field to be there.
  • The order of keys inside a filter does not change the result. Index design cares about the order of fields in the index, not in your filter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the filter { genre: "fantasy", inStock: true } return?

    Several fields in one filter document are combined with an implicit AND. You only need $and when the same key would otherwise appear twice.
  2. 2. Why is { $or: [A], $or: [B] } a bug in a JavaScript driver?

    The filter is built as a normal object before it is sent. The duplicate key is overwritten in your own code, so the server only ever receives the last $or. Wrap the clauses in $and instead.
  3. 3. A collection has one document without a price field. Does { price: { $not: { $gt: 20 } } } match it?

    $not inverts the inner condition. A missing field does not satisfy $gt, so the inverted condition is true. Add $exists: true if you need the field to exist.
  4. 4. Which filter means: none of the conditions may match?

    $nor takes an array of filters and matches documents that match none of them. $not works on one field's operator expression instead.

Summary

  • Several fields (or several operators on one field) in one filter are an implicit AND.
  • $and, $or and $nor each take an array of full filters; nesting them spells out grouping, so there are no precedence rules to memorize.
  • Never repeat a key in one filter object; use $and to combine two $or clauses or two conditions on the same field.
  • $not wraps one field's operator expression (or a regex) and also matches documents where the field is missing.
  • Negations such as $not, $nor, $ne and $nin include documents without the field and are rarely good index candidates.
  • Prefer $in over an $or of equalities on one field.

Next, learn to test whether a field exists and what type it has in Element and Evaluation Operators.