Comparison Operators
Compare values — equality, inequality, greater/less than.
← Previous | Index | Next: 11 - Boolean and Control Flow Operators →
Comparison operators are binary logical operators that compare two values and return a boolean result (or a numeric result in the case of $cmp).
$eq and $ne
Test for equality or inequality.
{ $eq: [<expr1>, <expr2>] } // true if expr1 === expr2
{ $ne: [<expr1>, <expr2>] } // true if expr1 !== expr2$gt, $gte, $lt, $lte
Greater than, greater-or-equal, less than, less-or-equal.
{ $gt: [<expr1>, <expr2>] } // true if expr1 > expr2
{ $gte: [<expr1>, <expr2>] } // true if expr1 >= expr2
{ $lt: [<expr1>, <expr2>] } // true if expr1 < expr2
{ $lte: [<expr1>, <expr2>] } // true if expr1 <= expr2Example: Filter by type and funding threshold
db.projects.aggregate([
{
$match: {
$expr: {
$and: [
{ $eq: ["$type", "REQUEST_FUNDING_PROJECT"] },
{ $lt: ["$projectFunding", 5000] }
]
}
}
},
{ $out: "projectReport" }
]);Note: When using comparison operators as expressions inside
$match, you must wrap them in$expr. See 14 - Variable and Reference Expressions for details on$expr.
$cmp — Numeric Comparison
Unlike the other comparison operators that return booleans, $cmp returns a number:
| Result | Meaning |
|---|---|
1 | First value is greater than the second |
-1 | First value is less than the second |
0 | Values are equal |
{ $cmp: [<expr1>, <expr2>] }Example
db.tweets.insertMany([
{ _id: 1, item: "abc1", qty: 300 },
{ _id: 2, item: "abc2", qty: 200 }
]);
db.tweets.aggregate([
{
$project: {
item: 1,
_id: 0,
cmpTo250: { $cmp: ["$qty", 250] }
}
}
]);Output:
{ item: "abc1", cmpTo250: 1 } // 300 > 250
{ item: "abc2", cmpTo250: -1 } // 200 < 250When to use
$cmp: When you need the comparison result as a sortable or computable number rather than a boolean — e.g., for scoring or ranking logic.