$ifNull (aggregation)

On this page

Definition

$ifNull

Evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value. If the expression evaluates to a null value, including instances of undefined values or missing fields, returns the value of the replacement expression.

The $ifNull expression has the following syntax:

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

The arguments can be any valid expression. For more information on expressions, see Expressions.

Example

The following example use a inventory collection with the following documents:

{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 }
{ "_id" : 2, "item" : "abc2", description: null, qty: 200 }
{ "_id" : 3, "item" : "xyz1", qty: 250 }

The following operation uses the $ifNull expression to return either the non-null description field value or the string "Unspecified" if the description field is null or does not exist:

db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            description: { $ifNull: [ "$description", "Unspecified" ] }
         }
      }
   ]
)

The operation returns the following results:

{ "_id" : 1, "item" : "abc1", "description" : "product 1" }
{ "_id" : 2, "item" : "abc2", "description" : "Unspecified" }
{ "_id" : 3, "item" : "xyz1", "description" : "Unspecified" }