$cmp (Compare)
Last updated: 2026-10-09
$cmp (Compare)
$cmp compares two values and returns -1, 0, or 1 for less than, equal, or greater than. It is the expression-form comparison operator, often used for custom sort keys or size checks inside $cond. Comparisons follow the BSON type ordering, so comparing different types does not throw — values are ordered by their type. Unlike $eq and $gt which return booleans, $cmp returns a three-way result that plugs directly into sorting logic or branching.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $cmp: [ <expression1>, <expression2> ] }
⚙️ Parameters
| expression 1 | The first expression to compare. |
|---|---|
| expression 2 | The second expression to compare. |
Returns:-1 when the first is less, 0 when equal, 1 when greater
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $cmp: compare two scores
db.scores.aggregate([
{ $project: {
result: { $cmp: ['$scoreA', '$scoreB'] }
} }
])
Output:
{ '_id': 1, 'result': 1 }
{ '_id': 2, 'result': -1 }
📌 Notes
- Returns three values (-1, 0, 1), not a boolean
- Different types compare by BSON type order without throwing
- Null orders before numbers in the type order
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat does $cmp return?
A-1 when the first is less, 0 when equal, and 1 when greater.
QHow do $cmp and $eq differ?
A$eq returns a boolean while $cmp returns a three-way result suited to sorting and branching.
QDoes $cmp throw when comparing different types?
ANo — it follows the BSON type order, so strings order after numbers.