Database Manual / Reference / Query Language / Expressions

$cond (expression operator)(表达式运算符)

Definition定义

$cond
Evaluates a boolean expression to return one of the two specified return expressions.计算布尔表达式以返回两个指定返回表达式之一。

Compatibility兼容性

You can use $cond for deployments hosted in the following environments:您可以将$cond用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

The $cond expression has one of two syntaxes:$cond表达式有两种语法之一:

{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }

Or:或者:

{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }

$cond requires all three arguments (if-then-else) for either syntax.这两种语法都需要所有三个参数(if-then-else)。

If the <boolean-expression> evaluates to true, then $cond evaluates and returns the value of the <true-case> expression. 如果<boolean-expression>的计算结果为true,则$cond计算并返回<true-case>表达式的值。Otherwise, $cond evaluates and returns the value of the <false-case> expression.否则,$cond将计算并返回<false-case>表达式的值。

The arguments can be any valid expression. 参数可以是任何有效的表达式For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Tip

$switch

Example示例

The following example use a inventory collection with the following documents:以下示例使用具有以下文档的inventory集合:

db.inventory.insertMany( [
{ _id: 1, item: "abc1", qty: 300 },
{ _id: 2, item: "abc2", qty: 200 },
{ _id: 3, item: "xyz1", qty: 250 }
] )

The following aggregation operation uses the $cond expression to set the discount value to 30 if qty value is greater than or equal to 250 and to 20 if qty value is less than 250:如果qty值大于或等于250,则以下聚合操作使用$cond表达式将discount值设置为30,如果qty值小于250,则设置为20

db.inventory.aggregate(
[
{
$project:
{
item: 1,
discount:
{
$cond: { if: { $gte: [ "$qty", 250 ] }, then: 30, else: 20 }
}
}
}
]
)

The operation returns the following results:该操作返回以下结果:

{ _id: 1, item: "abc1", discount: 30 }
{ _id: 2, item: "abc2", discount: 20 }
{ _id: 3, item: "xyz1", discount: 30 }

The following operation uses the array syntax of the $cond expression and returns the same results:以下操作使用$cond表达式的数组语法并返回相同的结果:

db.inventory.aggregate(
[
{
$project:
{
item: 1,
discount:
{
$cond: [ { $gte: [ "$qty", 250 ] }, 30, 20 ]
}
}
}
]
)