$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.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $cond: { if: <condition>, then: <result1>, else: <result2> } } or { $cond: [ <condition>, <result1>, <result2> ] }
⚙️ Parameters
| if/condition | The expression choosing a branch, judged by truthiness. |
|---|---|
| then/result 1 | The result when the condition is truthy. |
| else/result 2 | The 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
- The object and array forms are equivalent and interchangeable
- else is required and cannot be omitted
- For more than two branches, $switch reads better
🏷️ Related Tags
💡 Related Cases
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.