Concept Flow - Conditional expressions ($cond, $switch)
Start
$cond or $switch
Evaluate condition
Return ifTrue
Output value
The $cond or $switch expression evaluates conditions and returns values based on which condition is true.
db.collection.aggregate([
{ $project: {
status: { $cond: { if: { $gte: ["$score", 60] }, then: "Pass", else: "Fail" } }
}
}
])| Step | Input Document | Condition ($gte score,60) | Condition Result | Value Returned | Output Document |
|---|---|---|---|---|---|
| 1 | {"name":"Alice","score":85} | 85 >= 60 | True | "Pass" | {"name":"Alice","score":85,"status":"Pass"} |
| 2 | {"name":"Bob","score":55} | 55 >= 60 | False | "Fail" | {"name":"Bob","score":55,"status":"Fail"} |
| 3 | {"name":"Carol","score":60} | 60 >= 60 | True | "Pass" | {"name":"Carol","score":60,"status":"Pass"} |
| 4 | No more documents | - | - | - | Aggregation ends |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| score | - | 85 | 55 | 60 | - |
| conditionResult | - | True | False | True | - |
| status | - | "Pass" | "Fail" | "Pass" | - |
$cond syntax: { $cond: { if: <condition>, then: <trueValue>, else: <falseValue> } }
Evaluates condition; returns then if true, else if false.
$switch syntax: { $switch: { branches: [ { case: <cond>, then: <val> }, ... ], default: <val> } }
Checks multiple cases in order; returns first true then value or default.
Used in aggregation pipelines to create conditional fields.$cond operator do in a MongoDB aggregation pipeline?$cond in a MongoDB aggregation pipeline?status for a document with score: 75?
{
$addFields: {
status: {
$switch: {
branches: [
{ case: { $gte: ["$score", 90] }, then: "Excellent" },
{ case: { $gte: ["$score", 70] }, then: "Good" },
{ case: { $gte: ["$score", 50] }, then: "Average" }
],
default: "Poor"
}
}
}
}$switch:
{
$project: {
grade: {
$switch: {
branches: [
{ case: { $gt: ["$score", 90] }, then: "A" },
{ case: { $gt: ["$score", 80] }, then: "B" }
]
}
}
}
}$switch in an aggregation pipeline. Prices below 20 are "Cheap", 20 to 50 are "Moderate", above 50 are "Expensive". Which of the following $switch expressions correctly implements this?Pass the test and this pattern moves unknown