$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.

CategorySet, Condition & Conversion
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $switch: { branches: [ { case: <condition>, then: <result> }, ... ], default: <default> } }

⚙️ Parameters

branchesThe branch array; each item has a case condition and a then result.
defaultOptional 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏