定义
$switch对一系列 case 表达式求值。当它找到计算结果为
true的表达式时,$switch会执行指定表达式并脱离控制流。$switch通过以下语法实现:$switch: { branches: [ { case: <expression>, then: <expression> }, { case: <expression>, then: <expression> }, ... ], default: <expression> } branches数组中的对象必须仅包含case字段和then字段。
行为
各种案例语句不需要相互排斥。$switch 执行它找到的第一个评估为 true 的分支。如果所有分支评估都不为 true,则 $switch 执行 default 选项。
以下情况会导致 $switch 报错:
branches字段缺失或并非包含至少一个条目的数组。branches数组中的对象不包含case字段。branches数组中的对象不包含then字段。branches数组中的对象包含case或then以外的字段。未指定
default,也没有case评估为true。
例子 | 结果 | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
| |||||||||
|
| |||||||||
|
|
例子
一个名为 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!" }