On this page本页内容
$cond
Evaluates a boolean expression to return one of the two specified return expressions.计算布尔表达式以返回两个指定的返回表达式之一。
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.有关表达式的详细信息,请参阅表达式。
The following example use a 以下示例使用具有以下文档的inventory
collection with the following documents:inventory
集合:
{ "_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,则将discount
值设为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 ] } } } ] )