Docs 主页 → 开发应用程序 → MongoDB Manual
$switch(聚合)
定义
$switch
版本 3.4 中的新增功能。
对一系列 case 表达式求值。当它找到计算结果为
true
的表达式时,$switch
会执行指定表达式并脱离控制流。$switch
通过以下语法实现:$switch: { branches: [ { case: <expression>, then: <expression> }, { case: <expression>, then: <expression> }, ... ], default: <expression> } branches
数组中的对象必须仅包含case
字段和then
字段。
行为
各种 case 语句不需要相互排斥。 $switch
执行它找到的第一个评估为true
的分支。如果所有分支的计算结果都不为 true,则$switch
执行default
选项。
以下情况会导致$switch
失败并出现错误:
branches
字段缺失或并非包含至少一个条目的数组。branches
数组中的对象不包含case
字段。branches
数组中的对象不包含then
字段。branches
数组中的对象包含case
或then
以外的字段。未指定
default
,也没有case
评估为true
。
例子 | 结果 | |||||||||
---|---|---|---|---|---|---|---|---|---|---|
| "less than" | |||||||||
| "Did not match" | |||||||||
| "First case" |
例子
一个名为 grades
的集合包含以下文档:
{ "_id" : 1, "name" : "Susan Wilkes", "scores" : [ 87, 86, 78 ] } { "_id" : 2, "name" : "Bob Hanna", "scores" : [ 71, 64, 81 ] } { "_id" : 3, "name" : "James Torrelio", "scores" : [ 91, 84, 97 ] }
以下聚合操作使用$switch
显示基于每个学生平均分数的特定消息。
db.grades.aggregate( [ { $project: { "name" : 1, "summary" : { $switch: { branches: [ { case: { $gte : [ { $avg : "$scores" }, 90 ] }, then: "Doing great!" }, { case: { $and : [ { $gte : [ { $avg : "$scores" }, 80 ] }, { $lt : [ { $avg : "$scores" }, 90 ] } ] }, then: "Doing pretty well." }, { case: { $lt : [ { $avg : "$scores" }, 80 ] }, then: "Needs improvement." } ], default: "No scores found." } } } } ] )
该操作返回以下内容:
{ "_id" : 1, "name" : "Susan Wilkes", "summary" : "Doing pretty well." } { "_id" : 2, "name" : "Bob Hanna", "summary" : "Needs improvement." } { "_id" : 3, "name" : "James Torrelio", "summary" : "Doing great!" }