$cond
The $cond operator is a conditional (ifβthenβelse) operator.
It evaluates a condition and returns one of two expressions depending on whether the condition is true or false.
π Syntax
β Object Syntax
{
"$cond": {
"if": <condition>,
"then": <expression-if-true>,
"else": <expression-if-false>
}
}
β Array Syntax
{ "$cond": [ <condition>, <then>, <else> ] }
β Base Example 1 β Membership Status
π₯ Input Document
{ "isMember": true }
π Expression
{
"$cond": {
"if": "$isMember",
"then": "Discounted",
"else": "Regular"
}
}
π€ Output
"Discounted"
β Base Example 2 β Array Syntax
π₯ Input Document
{ "score": 65 }
π Expression
{ "$cond": [ { "$gte": ["$score", 70] }, "Pass", "Fail" ] }
π€ Output
"Fail"
π§± Ecommerce Example β Shipping Fee Waiver
π Pipeline
[
{ "$unwind": "$items" },
{
"$project": {
"name": "$items.name",
"shippingFee": {
"$cond": {
"if": { "$gte": ["$items.price", 100] },
"then": 0,
"else": 10
}
}
}
}
]
π₯ Input Document
{
"items": [
{ "name": "Monitor", "price": 150 },
{ "name": "Cable", "price": 20 }
]
}
π€ Output
[
{ "name": "Monitor", "shippingFee": 0 },
{ "name": "Cable", "shippingFee": 10 }
]
π§ Common Use Cases
- Apply different logic based on price, quantity, status
- Select values conditionally inside
$project,$group,$map - Use inside
$reduce,$switch,$filter
π Related Operators
$ifNull,$switch,$eq,$gt,$lt,$gte,$lte
π§ Notes
- Flexible control structure in aggregation pipelines
- Both array and object syntax are supported by MongoDB (and Fluxion)