$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:
- { $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:
- { "_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 toreturn either the non-null description
field value or the string"Unspecified"
if the description
field is null or does notexist:
- 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" }