- Reference >
- Operators >
- Aggregation Framework Operators >
- Conditional Aggregation Operators >
- $ifNull (aggregation)
$ifNull (aggregation)¶
-
$ifNull
¶ Takes an array with two expressions.
$ifNull
returns the first expression if it evaluates to a non-null
value. Otherwise,$ifNull
returns the second expression’s value.Use the
$ifNull
operator with the following syntax:Both values in the array specified to
$ifNull
must be valid MongoDB aggregation expressions or document fields. Do not use JavaScript in any aggregation statements, including$ifNull
.Example
The following aggregation on the
offSite
collection groups by thelocation
field and returns a count for each location. If thelocation
field containsnull
or does not exist, the$ifNull
returns"Unspecified"
as the value. MongoDB assigns the returned value to_id
in the aggregated document.