Navigation
This version of the documentation is archived and no longer supported.

$cond (aggregation)

$cond

$cond is a ternary operator that takes an array of three expressions, where 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.

Example

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