$switch (aggregation)

On this page本页内容

Definition定义

$switch

New in version 3.4.版本3.4中的新功能。

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字段。

Operand操作数Description描述
branches

An array of control branch documents. 控制分支文档的数组。Each branch is a document with the following fields:每个分支都是包含以下字段的文档:

  • case
    Can be any valid expression that resolves to a boolean. 可以是解析为boolean的任何有效表达式If the result is not a boolean, it is coerced to a boolean value. 如果结果不是boolean,则强制为布尔值。More information about how MongoDB evaluates expressions as either true or false can be found here.有关MongoDB如何将表达式计算为truefalse的更多信息,请参阅此处
  • then
    Can be any valid expression.可以是任何有效的表达式

The branches array must contain at least one branch document.branches数组必须至少包含一个分支文档。

default

Optional.可选。The path to take if no branch case expression evaluates to true.如果没有分支case表达式的计算结果为true,则采用的路径。

Although optional, if default is unspecified and no branch case evaluates to true, $switch returns an error.虽然可选,但如果default未指定,且没有分支大小写的计算结果为true,则$switch将返回一个错误。

Behavior行为

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失败并出现错误:

Example示例Results结果
{
   $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"

Example示例

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!" }

See also参阅

$cond