$switch(聚合)
定义
$switch评估一系列的案例表达式。当它找到一个求值为
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!" }