In MongoDB, $ifNull
is an aggregation pipeline operator that allows you to specify a value to use in place of null
.
The way that it works is, you provide an expression and a replacement expression. If the expression evaluates to a non-null value, that expression is returned. But if the expression evaluates to a null value, $ifNull
returns the value of the replacement expression.
A null value includes instances of undefined values or missing fields.
Example
Suppose we have a collection called test
with the following documents:
{ "_id" : 1, "data" : 250 } { "_id" : 2, "data" : -250 } { "_id" : 3, "data" : "Bucket" } { "_id" : 4, "data" : 0 } { "_id" : 5, "data" : ISODate("2021-01-03T23:30:15.100Z") } { "_id" : 6, "data" : null } { "_id" : 7, "data" : Infinity } { "_id" : 8, "data" : -Infinity }
Here’s what happens if we use the $ifNull
operator on the data
field:
db.test.aggregate(
[
{
$project:
{
result: { $ifNull: [ "$data", "Value not provided" ] }
}
}
]
)
Result:
{ "_id" : 1, "result" : 250 } { "_id" : 2, "result" : -250 } { "_id" : 3, "result" : "Bucket" } { "_id" : 4, "result" : 0 } { "_id" : 5, "result" : ISODate("2021-01-03T23:30:15.100Z") } { "_id" : 6, "result" : "Value not provided" } { "_id" : 7, "result" : Infinity } { "_id" : 8, "result" : -Infinity }
We can see that only one field had a null value and therefore, it was the only one that returned "Value not provided"
.
Undefined and Missing Fields
As mentioned, undefined values and missing fields are treated as null values.
Suppose we add the following documents to our collection:
{ "_id" : 9, "data" : undefined } { "_id" : 10, "name" : "Homer" }
In this case, document 9 has undefined
in the data field, but document 10 doesn’t even have a data
field.
Here’s what happens when we apply $ifNull
to those documents:
db.test.aggregate(
[
{ $match: { _id: { $in: [ 9, 10 ] } } },
{
$project:
{
result: { $ifNull: [ "$data", "Value not provided" ] }
}
}
]
)
Result:
{ "_id" : 9, "result" : "Value not provided" } { "_id" : 10, "result" : "Value not provided" }