$switch (aggregation)

在本页面

Definition

计算一系列案例表达式。当它找到一个计算结果为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失败并显示错误:

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

$cond

首页