How to Use $switch in Aggregation in MongoDB
Use the
$switch operator inside a MongoDB aggregation pipeline to evaluate multiple conditions and return a value for the first true case. It works like a switch-case statement, with branches for conditions and a default value if no conditions match.Syntax
The $switch operator has this structure:
branches: An array of objects, each withcase(a condition) andthen(the value to return if the case is true).default: The value to return if none of the cases are true.
json
{
$switch: {
branches: [
{ case: <expression>, then: <value> },
{ case: <expression>, then: <value> },
...
],
default: <value>
}
}Example
This example shows how to use $switch to categorize scores into grades inside an aggregation pipeline.
mongodb
db.students.aggregate([
{
$project: {
name: 1,
score: 1,
grade: {
$switch: {
branches: [
{ case: { $gte: ["$score", 90] }, then: "A" },
{ case: { $gte: ["$score", 80] }, then: "B" },
{ case: { $gte: ["$score", 70] }, then: "C" },
{ case: { $gte: ["$score", 60] }, then: "D" }
],
default: "F"
}
}
}
}
])Output
[
{ "_id": ObjectId("..."), "name": "Alice", "score": 85, "grade": "B" },
{ "_id": ObjectId("..."), "name": "Bob", "score": 72, "grade": "C" },
{ "_id": ObjectId("..."), "name": "Charlie", "score": 59, "grade": "F" }
]
Common Pitfalls
- Forgetting to include the
defaultvalue can causenullresults when no cases match. - Conditions must be valid MongoDB expressions; using incorrect syntax causes errors.
- The
branchesarray is evaluated in order; the first truecasestops evaluation.
json
/* Wrong: missing default, so unmatched cases return null */ { $switch: { branches: [ { case: { $eq: ["$status", "active"] }, then: "Active" } ], default: null } } /* Right: add default to handle unmatched cases */ { $switch: { branches: [ { case: { $eq: ["$status", "active"] }, then: "Active" } ], default: "Inactive" } }
Quick Reference
| Part | Description |
|---|---|
| $switch | Operator to evaluate multiple conditions and return a value. |
| branches | Array of { case: condition, then: value } objects. |
| case | Condition expression to test. |
| then | Value returned if the case is true. |
| default | Value returned if no cases match. |
Key Takeaways
Use $switch to handle multiple conditional branches in aggregation pipelines.
Always include a default value to avoid null results when no cases match.
Branches are checked in order; the first true case determines the output.
Conditions inside case must be valid MongoDB expressions.
$switch helps simplify complex conditional logic inside aggregation stages.