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

$ifNull (aggregation)


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:

{ $ifNull: [ <expression>, <replacement-if-null> ] }

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.


The following aggregation on the offSite collection groups by the location field and returns a count for each location. If the location field contains null or does not exist, the $ifNull returns "Unspecified" as the value. MongoDB assigns the returned value to _id in the aggregated document.

         $group: {
            _id: { $ifNull: [ "$location", "Unspecified" ] },
            count: { $sum: 1 }