参考 > 参考 > 经营者 > 聚合管道运营商 > $ cond(汇总)
在本页面
$cond
计算一个布尔表达式以返回两个指定的返回表达式之一。
该$cond表达式具有以下两种语法之一:
{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }
要么:
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
$cond要求if-then-else使用任何一种语法的所有三个参数()。
if-then-else
如果将<boolean-expression>计算结果为true,则 $cond计算并返回<true-case>表达式的值 。否则,$cond求值并返回<false-case>表达式的值。
<boolean-expression>
true
<true-case>
<false-case>
参数可以是任何有效的表达式。有关表达式的更多信息,请参见 表达式。
也可以看看
$switch
以下示例将inventory集合与以下文档一起使用:
inventory
{ "_id" : 1, "item" : "abc1", qty: 300 } { "_id" : 2, "item" : "abc2", qty: 200 } { "_id" : 3, "item" : "xyz1", qty: 250 }
以下聚合操作使用该$cond 表达式将discountvalue 设置为30if qtyvalue大于或等于250以及20if qtyvalue小于250:
discount
30
qty
20
250
db.inventory.aggregate( [ { $project: { item: 1, discount: { $cond: { if: { $gte: [ "$qty", 250 ] }, then: 30, else: 20 } } } } ] )
该操作返回以下结果:
{ "_id" : 1, "item" : "abc1", "discount" : 30 } { "_id" : 2, "item" : "abc2", "discount" : 20 } { "_id" : 3, "item" : "xyz1", "discount" : 30 }
以下操作使用$cond表达式的数组语法, 并返回相同的结果:
db.inventory.aggregate( [ { $project: { item: 1, discount: { $cond: [ { $gte: [ "$qty", 250 ] }, 30, 20 ] } } } ] )