$cond (aggregation)

Definition

  • $cond
  • Evaluates a boolean expression to return one of the two specifiedreturn expressions.

The $cond expression has one of two syntaxes:

New in version 2.6.

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

Or:

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

$cond requires all three arguments (if-then-else)for either syntax.

If the <boolean-expression> evaluates to true, then$cond evaluates and returns the value of the<true-case> expression. Otherwise, $cond evaluatesand returns the value of the <false-case> expression.

The arguments can be any valid expression. For more information on expressions, seeExpressions.

See also

$switch

Example

The following example use a inventory collection with the followingdocuments:

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

The following aggregation operation uses the $condexpression to set the discount value to 30 if qty value isgreater than or equal to 250 and to 20 if qty value is lessthan 250:

  1. db.inventory.aggregate(
  2. [
  3. {
  4. $project:
  5. {
  6. item: 1,
  7. discount:
  8. {
  9. $cond: { if: { $gte: [ "$qty", 250 ] }, then: 30, else: 20 }
  10. }
  11. }
  12. }
  13. ]
  14. )

The operation returns the following results:

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

The following operation uses the array syntax of the$cond expression and returns the same results:

  1. db.inventory.aggregate(
  2. [
  3. {
  4. $project:
  5. {
  6. item: 1,
  7. discount:
  8. {
  9. $cond: [ { $gte: [ "$qty", 250 ] }, 30, 20 ]
  10. }
  11. }
  12. }
  13. ]
  14. )