$cond (Conditional Expression)

Last updated: 2026-10-09

$cond (Conditional Expression)

$cond implements if-then-else ternary logic, the most basic branching operator in aggregation expressions. It supports an object form { if, then, else } and an array form [ condition, trueResult, falseResult ], which are equivalent. Typical uses: computing shipping tiers from order amounts or mapping status codes to labels. The condition follows truthiness rules, so non-boolean values work too. For many branches, $switch is clearer.

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

📝 Syntax

{ $cond: { if: <condition>, then: <result1>, else: <result2> } } or { $cond: [ <condition>, <result1>, <result2> ] }

⚙️ Parameters

if/conditionThe expression choosing a branch, judged by truthiness.
then/result 1The result when the condition is truthy.
else/result 2The result when the condition is falsy.

Returns:result1 when the condition is truthy, otherwise result2

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $cond: amounts over 100 are big orders
db.orders.aggregate([
  { $project: {
      level: { $cond: { if: { $gt: ['$amount', 100] }, then: 'big', else: 'small' } }
  } }
])

Output:

{ '_id': 1, 'level': 'big' }
{ '_id': 2, 'level': 'small' }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QCan the condition be non-boolean?
AYes — truthiness applies; 0, null and '' are falsy.
QWhat is the difference between the two forms?
ANone — semantics are identical, only the syntax differs.
QHow do I handle many branches?
AUse $switch, which matches the first truthy branch in order.
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%

🙏 帮我们做得更好

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

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