Comparison operators
Comparison operators test values against numbers, strings or dates.
In this page:
Syntax
{ field: { $eq: value } }
{ field: { $ne: value } }
{ field: { $gte: value, $lt: value } }
{ field: { $in: [value1, value2] } }
Comparison operators
$eq, $ne, $gt, $gte, $lt, $lte, $in and $nin cover most comparisons. Comparisons follow BSON type ordering, so numbers do not match strings that look like numbers. Dates compare chronologically.
Note:
A string "30" does not match the number 30.
Example: Comparison operators
test> db.scores.insertMany([{ _id: 1, s: 50 }, { _id: 2, s: "50" }, { _id: 3, s: 75 }, { _id: 4 }])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.scores.find({ s: 50 })
[ { _id: 1, s: 50 } ]
test> db.scores.find({ s: { $gt: 60 } })
[ { _id: 3, s: 75 } ]
test> db.scores.find({ s: { $ne: 50 } })
[ { _id: 2, s: '50' }, { _id: 3, s: 75 }, { _id: 4 } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Comparing numbers stored as strings
- Using $ne and forgetting it also matches missing fields
- Comparing dates as strings
Chapter Summary
- $eq $ne $gt $gte $lt $lte
- $in and $nin for lists
- Types must match
- $ne matches missing fields too
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: