对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

$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 评估为真,则 $switch 会返回错误。

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

以下情况会导致 $switch 报错:

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

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

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

  • branches 数组中的对象包含 case 或 then 以外的字段。

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

以下示例使用 sample_mflix 示例数据集中的 movies 集合。有关如何将此数据集加载到部署中的详细信息,请参阅 加载示例数据集。

此聚合操作使用 $switch 显示基于每部电影评分的特定消息。$match 阶段将结果限制为示例数据集中的三部最长电影:

db.movies.aggregate( [ { $match: { runtime: { $gt: 800 } } }, { $project: { _id: 0, title: 1, summary: { $switch: { branches: [ { case: { $gte: [ "$imdb.rating", 9 ] }, then: "Doing great!" }, { case: { $and: [ { $gte: [ "$imdb.rating", 8 ] }, { $lt: [ "$imdb.rating", 9 ] } ] }, then: "Doing pretty well." }, { case: { $lt: [ "$imdb.rating", 8 ] }, then: "Needs improvement." } ], default: "No rating found." } } } }, { $sort: { title: 1 } }] )
[ { title: 'Baseball', summary: 'Doing great!' }, { title: 'Centennial', summary: 'Doing pretty well.' }, { title: 'Taken', summary: 'Needs improvement.' }]

提示

$cond

给本页内容打分

在此页面上