Comparison Operators: $eq, $ne, $gt, $gte, $lt, $lte
"Books under 8", "books after 1950", "anything not out of stock". Almost every shop filter compares a field with a value. MongoDB spells each comparison as a small operator document placed where a plain value would go.
The rule
Swap the value for an operator document:
{ field: { $op: value } }.
| _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 |
| Operator | Means | price example |
Matches |
|---|---|---|---|
$eq |
equal to | { $eq: 12 } |
Circe |
$ne |
not equal to | { $ne: 12 } |
the other four |
$gt |
greater than | { $gt: 8 } |
Dune, Neuromancer, Circe |
$gte |
greater than or equal | { $gte: 9.99 } |
Dune, Circe |
$lt |
less than | { $lt: 5 } |
Emma |
$lte |
less than or equal | { $lte: 7.99 } |
Emma, The Hobbit |
{ price: 12 }is shorthand for{ price: { $eq: 12 } }.- Ranges put two operators in one document:
{ year: { $gte: 1900, $lt: 2000 } }. - On an array field, a comparison matches if any element passes; on an array of objects use a dotted path:
{ "ratings.score": { $gt: 4 } }finds Dune and The Hobbit, which each have a 5. $nealso matches documents where the field is missing.{ signed: { $ne: true } }returns the four books with nosignedfield.
The shortcut
Translate the English word by word: "over" → $gt, "at least" → $gte, "under" → $lt, "at most" → $lte, "not" → $ne. Then gather every condition on one field into one braces pair.
Translate each phrase
"at least 1900" →
$gte: 1900. "under 2000" →$lt: 2000.
The trap: { year: { $gte: 1900 }, year: { $lt: 2000 } }. A JavaScript object cannot hold the same key twice, so the second year silently replaces the first, and Emma (1815) slips in.
Drills
Answer fast — trust the rule.
How many books match { stock: { $lte: 3 } }?
Which filter means "price over 9.99"?
How many books does { year: { $gte: 1900 }, year: { $lt: 2000 } } return?
How many books match { signed: { $ne: true } }?
Which books match { "ratings.score": { $gt: 4 } }?
Remember
- Swap the value for an operator document:
{ field: { $op: value } }. - Shortcut: translate over, at least, under, at most, not; keep one field's conditions in one braces pair.
- Trap: a repeated key silently drops a condition, and
$nealso matches missing fields.
