Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$switch(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$switch

对一系列 case 表达式求值。当它找到计算结果为 true 的表达式时,$switch 会执行指定表达式并脱离控制流。

$switch 通过以下语法实现:

$switch: {
branches: [
{ case: <expression>, then: <expression> },
{ case: <expression>, then: <expression> },
...
],
default: <expression>
}

branches 数组中的对象必须仅包含 case 字段和 then 字段。

操作数
说明
branches

控制分支文档的数组。每个分支均为一个包含以下字段的文档:

  • case
    可以是解析为 boolean 的任何有效表达式。如果结果不是 boolean,则会将其强制转换为布尔值。请访问此处,查看 MongoDB 如何将表达式求值为真或假。
  • then
    可以是任何有效表达式

branches 数组必须至少包含一份分支文档。

default

可选。在没有分支 case 表达式评估为 true 的情况下所采用的路径。

尽管可选,但如果未指定default且没有分支case的计算结果为 true,则$switch会返回错误。

各种 case 语句不需要相互排斥。 $switch执行它找到的第一个评估为true的分支。如果所有分支的计算结果都不为 true,则$switch执行default选项。

以下情况会导致$switch失败并出现错误:

  • branches 字段缺失或并非包含至少一个条目的数组。

  • branches 数组中的对象不包含 case 字段。

  • branches 数组中的对象不包含 then 字段。

  • branches 数组中的对象包含 casethen 以外的字段。

  • 未指定 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"

一个名为 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!" }

提示

另请参阅:

← $sum(聚合)

在此页面上