定义
$switch对一系列 case 表达式求值。当它找到计算结果为
true的表达式时,$switch会执行指定表达式并脱离控制流。$switch通过以下语法实现:$switch: { branches: [ { case: <expression>, then: <expression> }, { case: <expression>, then: <expression> }, ... ], default: <expression>}branches数组中的对象必须仅包含case字段和then字段。
行为
各种案例语句不需要相互排斥。$switch 执行它找到的第一个评估为 true 的分支。如果所有分支评估都不为 true,则 $switch 执行 default 选项。
以下情况会导致 $switch 报错:
branches字段缺失或并非包含至少一个条目的数组。branches数组中的对象不包含case字段。branches数组中的对象不包含then字段。branches数组中的对象包含case或then以外的字段。未指定
default,也没有case评估为true。
例子 | 结果 |
|---|---|
|
|
|
|
|
|
例子
以下示例使用 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.' }]提示