文档菜单
文档首页
/
MongoDB 手册
/ / /

$switch(聚合)

在本页

  • 定义
  • 行为
  • 示例
$switch

评估一系列的案例表达式。当它找到一个求值为 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 将返回一个错误。

各种情况语句不必互斥。 $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" }
]
}
}
"小于"
{
$switch: {
branches: [
{ case: { $eq: [ 0, 5 ] }, then: "equals" },
{ case: { $gt: [ 0, 5 ] }, then: "greater than" }
],
default: "Did not match"
}
}
"不匹配"
{
$switch: {
branches: [
{ case: "this is true", then: "first case" },
{ case: false, then: "second case" }
],
default: "Did not match"
}
}
"第一个情况"

名为 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