$cond (aggregation)

On this page本页内容

Definition定义

$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.$cond需要这两种语法的所有三个参数(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.有关表达式的详细信息,请参阅表达式

See also参阅

$switch

Example示例

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:以下聚合操作使用$cond表达式将discount值设置为30(如果qty值大于或等于250),并将discount值设置为20(如果数量值小于250):

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