How to Use $cond in Aggregation in MongoDB: Syntax and Examples
In MongoDB aggregation, use the
$cond operator to apply conditional logic within a pipeline stage. It takes three parts: a condition, a value if true, and a value if false, allowing you to return different results based on the condition.Syntax
The $cond operator has this form inside an aggregation pipeline:
- if: The condition to check (expression that returns true or false).
- then: The value to return if the condition is true.
- else: The value to return if the condition is false.
You can write it as an object with if, then, and else fields or as an array with three elements: condition, true case, false case.
json
{
$cond: {
if: <condition>,
then: <value_if_true>,
else: <value_if_false>
}
}
// Or as an array:
{
$cond: [ <condition>, <value_if_true>, <value_if_false> ]
}Example
This example shows how to use $cond in an aggregation pipeline to add a new field status that says "Adult" if age is 18 or more, and "Minor" otherwise.
mongodb
db.people.aggregate([
{
$addFields: {
status: {
$cond: {
if: { $gte: ["$age", 18] },
then: "Adult",
else: "Minor"
}
}
}
}
])Output
[
{ "_id": 1, "name": "Alice", "age": 25, "status": "Adult" },
{ "_id": 2, "name": "Bob", "age": 16, "status": "Minor" },
{ "_id": 3, "name": "Charlie", "age": 18, "status": "Adult" }
]
Common Pitfalls
Common mistakes when using $cond include:
- Using incorrect syntax, like missing the
if,then, orelsekeys when using the object form. - Confusing the order of elements when using the array form.
- Not using expressions properly inside the condition, such as forgetting to use
$gteor other operators. - Expecting
$condto work outside aggregation pipelines.
json
/* Wrong: missing 'if' key */ { $cond: { then: "Adult", else: "Minor" } } /* Correct: include 'if' key */ { $cond: { if: { $gte: ["$age", 18] }, then: "Adult", else: "Minor" } }
Quick Reference
| Part | Description | Example |
|---|---|---|
| if | Condition to evaluate (true/false) | { $gte: ["$age", 18] } |
| then | Value if condition is true | "Adult" |
| else | Value if condition is false | "Minor" |
Key Takeaways
Use $cond in aggregation to return values based on a condition.
You can write $cond as an object with if/then/else or as an array with three elements.
Always ensure the condition expression is valid and returns a boolean.
Common errors include missing keys or wrong order in the array form.
$cond works only inside aggregation pipeline stages like $project or $addFields.