Docs Menu
Docs Home
/
MongoDB Manual
/ / /

$ifNull (aggregation)

On this page

  • Definition
  • Compatibility
  • Syntax
  • Example
$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 evaluates input expressions for null values and returns:

  • The first non-null input expression value found.

  • A replacement expression value if all input expressions evaluate to null.

$ifNull treats undefined values and missing fields as null.

You can use $ifNull for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

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

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

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" }

Back

$hour (aggregation)