OPTIONS

$cond (aggregation)

Definition

$cond

$cond is a ternary operator that takes three expressions and evaluates the first expression to determine which of the subsequent expressions to return. $cond accepts input either as an array with three items, or as an object.

New in version 2.6: $cond now accepts expressions in the form of documents.

Syntax

Document

New in version 2.6: $cond adds support for the document format.

When $cond takes a document, the document has three fields: if, then, and else. Consider the following example:

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

The if field takes an expression that evaluates to a Boolean value. If the expression evaluates to true, then $cond evaluates and returns the value of the then field. Otherwise, $cond evaluates and returns the value of the else field.

The expressions in the if, then, and else fields may be valid MongoDB aggregation expressions. You cannot use JavaScript in the expressions.

Array

When you specify $cond as an array of three expressions, the first expression evaluates to a Boolean value. If the first expression evaluates to``true``, then $cond evaluates and returns the value of the second expression. If the first expression evaluates to false, then $cond evaluates and returns the third expression.

Use the $cond operator with the following syntax:

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

All three values in the array specified to $cond must be valid MongoDB aggregation expressions or document fields. Do not use JavaScript in any aggregation statements, including $cond.

Examples

Specify $cond Expression as a Document

The following aggregation pipeline operation returns a weightedCount for each item_id. The $sum operator uses the $cond expression to add 2 if the value stored in the level field is E and 1 otherwise.

db.survey.aggregate(
   [
      {
         $group: {
            _id: "$item_id",
            weightedCount: { $sum: { $cond: { if: { $eq: [ "$level", "E" ] } ,
                                              then: 2,
                                              else: 1
                                            } } }
         }
      }
   ]
)

Specify a $cond Expression using an Array

The following aggregation on the survey collection groups by the item_id field and returns a weightedCount for each item_id. The $sum operator uses the $cond expression to add either 2 if the value stored in the level field is E and 1 otherwise.

db.survey.aggregate(
   [
      {
         $group: {
            _id: "$item_id",
            weightedCount: { $sum: { $cond: [ { $eq: [ "$level", "E" ] } , 2, 1 ] } }
         }
      }
   ]
)