On this page
$switch (aggregation)
在本页面
Definition
$switch
- 3.4 版的新功能。
计算一系列案例表达式。当它找到一个计算结果为true
的表达式时,$switch
执行指定的表达式并退出控制流程。
$switch具有以下语法:
$switch: {
branches: [
{ case: <expression>, then: <expression> },
{ case: <expression>, then: <expression> },
...
],
default: <expression>
}
branches
数组中的对象必须仅包含case
字段和then
字段。
Operand | Description |
---|---|
branches |
控件分支文档的数组。每个分支都是一个具有以下字段的文档: |
case
可以是任何可解析为boolean
的有效expression。如果结果不是boolean
,则将其强制为布尔值。有关 MongoDB 如何将表达式评估为 true 或 false 的更多信息,请参见here。then
可以是任何有效的expression。branches
数组必须至少包含一个分支文档。
| default
|可选。如果没有分支case
表达式的求值路径为true
。
尽管是可选的,但如果未指定default
并且没有分支case
求值为 true,则$switch返回错误。
Behavior
各种 case 语句不必相互排斥。 $switch执行找到的第一个分支,其结果为true
。如果所有分支的计算结果都不为 true,则$switch执行default
选项。
以下情况导致$switch失败并显示错误:
branches
字段丢失或不是具有至少一个条目的数组。branches
数组中的对象不包含case
字段。branches
数组中的对象不包含then
字段。branches
数组中的对象包含case
或then
以外的其他字段。未指定
default
,也没有case
计算为true
。
Example | Results |
---|---|
{ | |
$switch: { branches: [ { case: { $eq: [ 0, 5] },然后:“等于”}, { case: { $gt: [ 0, 5] },然后:“大于”}, { case: { $lt: [ 0, 5] },然后:“小于”} ] } } |
"less than" |
{ $switch: { branches: [ { case: { $eq: [ 0, 5] },然后:“等于”}, { case: { $gt: [ 0, 5] },然后:“大于”} ], 默认值:“不匹配” } } |
"Did not match" |
{ $switch: { branches: [ { case: "this is true", then: "first case" }, { case: false, then: "second case" } |
|
br], 默认值:“不匹配” } } |
"First case" |
Example
名为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!" }
See also