$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.

CategorySet, Condition & Conversion
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $cmp: [ <expression1>, <expression2> ] }

⚙️ Parameters

expression 1The first expression to compare.
expression 2The 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏