$cond (aggregation)

在本页面

Definition

  • $cond
    • 计算一个布尔表达式以返回两个指定的返回表达式之一。

$cond表达式具有以下两种语法之一:

2.6 版的新功能。

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

Or:

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

$cond要求使用这三个语法的所有三个参数(if-then-else)。

如果<boolean-expression>评估为true,则$cond评估并返回<true-case>表达式的值。否则,$cond计算并返回<false-case>表达式的值。

参数可以是任何有效的expression。有关表达式的更多信息,请参见Expressions

See also

Example

以下示例将inventory集合与以下文档一起使用:

{ "_id" : 1, "item" : "abc1", qty: 300 }
{ "_id" : 2, "item" : "abc2", qty: 200 }
{ "_id" : 3, "item" : "xyz1", qty: 250 }

以下聚合操作使用$cond表达式,如果qty值大于或等于 250,则将discount值设置为30,如果qty值小于250则将_设置为20

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 ]
               }
           }
      }
   ]
)