On this page本页内容
$switch
Evaluates a series of case expressions. 计算一系列大小写表达式。When it finds an expression which evaluates to 当它找到一个计算结果为true
, $switch
executes a specified expression and breaks out of the control flow.true
的表达式时,$switch
将执行一个指定的表达式并中断控制流。
$switch
has the following syntax:语法如下:
$switch: { branches: [ { case: <expression>, then: <expression> }, { case: <expression>, then: <expression> }, ... ], default: <expression> }
The objects in the branches
array must contain only a case
field and a then
field.branches
数组中的对象只能包含一个case
字段和一个then
字段。
branches |
|
default |
|
The various case statements do not need to be mutually exclusive. 各种案例陈述不需要相互排斥。$switch
executes the first branch it finds which evaluates to 执行它找到的第一个分支,其计算结果为true
. true
。If none of the branches evaluates to true, 如果没有分支的计算结果为$switch
executes the default
option.true
,$switch
将执行默认选项。
The following conditions cause 以下情况导致$switch
to fail with an error:$switch
失败并出现错误:
branches
field is missing or is not an array with at least one entry.branches
字段缺失或不是至少有一个条目的数组。branches
array does not contain a case
field.branches
数组中的对象不包含case
字段。branches
array does not contain a then
field.branches
数组中的对象不包含then
字段。branches
array contains a field other than case
or then
.branches
数组中的对象包含case
或then
以外的字段。default
is specified and no case
evaluates to true
.default
,也没有case
计算为true
。{ $switch: { branches: [ { case: { $eq: [ 0, 5 ] }, then: "equals" }, { case: { $gt: [ 0, 5 ] }, then: "greater than" }, { case: { $lt: [ 0, 5 ] }, then: "less than" } ] } } | "less than" |
{ $switch: { branches: [ { case: { $eq: [ 0, 5 ] }, then: "equals" }, { case: { $gt: [ 0, 5 ] }, then: "greater than" } ], default: "Did not match" } } | "Did not match" |
{ $switch: { branches: [ { case: "this is true", then: "first case" }, { case: false, then: "second case" } ], default: "Did not match" } } | "First case" |
A collection named 名为grades
contains the following documents: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 ] }
The following aggregation operation uses 以下聚合操作使用$switch
to display a particular message based on each student's average score.$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." } } } } ] )
The operation returns the following:运算结果如下:
{ "_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!" }