定义
兼容性
可以使用 $cond 查找托管在以下环境中的部署:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
The $cond expression has one of two syntaxes:
{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }
或者:
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
$cond requires all three arguments (if-then-else) for either syntax.
If the <boolean-expression> evaluates to true, then $cond evaluates and returns the value of the <true-case> expression. Otherwise, $cond evaluates and returns the value of the <false-case> expression.
参数可以是任何有效表达式。
提示
示例
本页上的示例使用来自 sample_mflix 数据集的数据。有关如何将此数据集加载到您的自管理 MongoDB 部署中的详细信息,请参阅 加载示例数据集。如果您对示例数据库进行了任何修改,您可能需要删除并重新创建数据库,才能运行此页面上的示例。
The following aggregation operation uses the $cond expression to assign a rental price to each movie. The operation prices movies with an imdb.rating greater than or equal to 9 at 5.99. The operation prices all other movies at 3.99:
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $project: { title: 1, rentalPrice: { $cond: { if: { $gte: [ "$imdb.rating", 9 ] }, then: 5.99, else: 3.99 } } } } ] )
[ { _id: ..., title: 'Baseball', rentalPrice: 5.99 }, { _id: ..., title: 'Centennial', rentalPrice: 3.99 } ]
The following operation uses the array syntax of the $cond expression and returns the same results:
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $project: { title: 1, rentalPrice: { $cond: [ { $gte: [ "$imdb.rating", 9 ] }, 5.99, 3.99 ] } } } ] )