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

$cond(表达式操作符)

$cond

计算布尔表达式,返回两个指定的返回表达式之一。

可以使用 $cond 查找托管在以下环境中的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

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.

参数可以是任何有效表达式。

提示

$switch

本页上的示例使用来自 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
]
}
}
}
] )
给本页内容打分