$switch (Multi-branch Conditional)
Last updated: 2026-10-09
$switch (Multi-branch Conditional)
$switch evaluates multiple case branches in order and returns the then result of the first case that is true, like a programming-language switch statement. When no branch matches, it returns default; omitting default when nothing matches throws an error. Typical uses: mapping order status codes to labels or grading scores into bands. Each case follows truthiness rules. Compared with nested $cond, $switch reads better and supports unlimited branches.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $switch: { branches: [ { case: <condition>, then: <result> }, ... ], default: <default> } }
⚙️ Parameters
| branches | The branch array; each item has a case condition and a then result. |
|---|---|
| default | Optional value returned when no case matches. |
Returns:The then of the first truthy case, or default when none match
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $switch: tier orders by amount
db.orders.aggregate([
{ $project: {
tier: { $switch: { branches: [
{ case: { $gte: ['$amount', 1000] }, then: 'gold' },
{ case: { $gte: ['$amount', 100] }, then: 'silver' }
], default: 'bronze' } }
} }
])
Output:
{ '_id': 1, 'tier': 'silver' }
{ '_id': 2, 'tier': 'bronze' }
📌 Notes
- Branches evaluate in order and stop at the first truthy one
- Missing default with no matching branch throws; always provide it in production
- Cases follow truthiness rules, so non-boolean expressions are fine
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat happens when no branch matches?
AIt returns default; without default it throws, so always provide one.
QIs $switch better than nested $cond?
A$switch reads better with many branches, keeping logic flat.
QAre all cases evaluated?
ANo — evaluation short-circuits at the first match.