$ifNull (aggregation)

Definition

  • $ifNull
  • Evaluates an expression and returns the value of the expression ifthe expression evaluates to a non-null value. If the expressionevaluates to a null value, including instances of undefined valuesor missing fields, returns the value of the replacement expression.

The $ifNull expression has the following syntax:

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

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

Example

The following example use a inventory collection with the followingdocuments:

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

The following operation uses the $ifNull expression toreturn either the non-null description field value or the string"Unspecified" if the description field is null or does notexist:

  1. db.inventory.aggregate(
  2. [
  3. {
  4. $project: {
  5. item: 1,
  6. description: { $ifNull: [ "$description", "Unspecified" ] }
  7. }
  8. }
  9. ]
  10. )

The operation returns the following results:

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