Comparison operators let you filter documents by evaluating field values against a specified value. They are the backbone of every non-trivial query in MongoDB.
General Syntax
// Standard form — field compared against operator value db.collection.find({ field: { $operator: value } }) // Shorthand equality — no operator needed db.collection.find({ field: value })
All Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
$eq |
Equal to | { age: { $eq: 30 } } |
$ne |
Not equal to (includes missing field) | { status: { $ne: "inactive" } } |
$gt |
Greater than | { price: { $gt: 100 } } |
$gte |
Greater than or equal to | { score: { $gte: 90 } } |
$lt |
Less than | { qty: { $lt: 10 } } |
$lte |
Less than or equal to | { rating: { $lte: 3 } } |
$in |
Matches any value in array | { color: { $in: ["red","blue"] } } |
$nin |
Matches none of the values in array (includes missing field) | { role: { $nin: ["admin","root"] } } |
$cmp |
Aggregation only — returns -1, 0, or 1 | { $cmp: ["$price", 100] } |
Where Comparison Operators Are Used
Comparison operators work identically across all contexts that accept a query filter:
find()andfindOne()— primary read filterupdateOne()/updateMany()— the first argument (filter)deleteOne()/deleteMany()— the filter argument- Aggregation pipeline
$matchstage — same syntax asfind()
$cmp is exclusively an aggregation expression operator and cannot be used in find() filters. Use it inside $project, $addFields, or $match with $expr.