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