MongoDB $ifNull: Null, Missing Fields, and Multiple Fallbacks
MongoDB $ifNull returns the first non-null expression it finds. If every input expression is null, missing, or undefined, it returns the final replacement expression.
It is commonly used in aggregation pipelines to provide defaults for optional fields.
Syntax
A single fallback:
{ $ifNull: [ <input-expression>, <replacement-expression> ] }
MongoDB 5.0 and later also support multiple input expressions:
{
$ifNull: [
<input-expression-1>,
<input-expression-2>,
...,
<replacement-expression>
]
}
The first non-null input is returned. Missing fields are treated as null by $ifNull.
Example: replace null or missing values
Suppose students contains:
{ "_id": 1, "name": "Tom", "score": 80 }
{ "_id": 2, "name": "Jerry", "score": null }
{ "_id": 3, "name": "Alice" }
Project a default score of 0:
db.students.aggregate([
{
$project: {
name: 1,
score: { $ifNull: ["$score", 0] }
}
}
])
Result:
{ "_id": 1, "name": "Tom", "score": 80 }
{ "_id": 2, "name": "Jerry", "score": 0 }
{ "_id": 3, "name": "Alice", "score": 0 }Example: use multiple fallback fields
For contact data, prefer workPhone, then mobilePhone, then a text fallback:
db.customers.aggregate([
{
$project: {
name: 1,
preferredPhone: {
$ifNull: [
"$workPhone",
"$mobilePhone",
"No phone"
]
}
}
}
])
Multiple input expressions are especially useful when older documents and newer documents store equivalent data under different fields.
Example: use $ifNull inside a calculation
db.orders.aggregate([
{
$project: {
item: 1,
quantity: { $ifNull: ["$quantity", 0] },
unitPrice: { $ifNull: ["$unitPrice", 0] },
total: {
$multiply: [
{ $ifNull: ["$quantity", 0] },
{ $ifNull: ["$unitPrice", 0] }
]
}
}
}
])
This prevents a missing or null operand from propagating into the calculation.
$ifNull vs $cond
Use $ifNull when the decision is specifically “use this value unless it is null/missing.”
Use $cond when the decision depends on another boolean expression:
{
$cond: [
{ $gte: ["$score", 60] },
"pass",
"fail"
]
}
For more than two conditional branches, use $switch.
Common mistakes
Treating an empty string as null
"", 0, and false are values, not null. $ifNull does not replace them automatically.
Confusing aggregation null handling with query matching
$ifNull is an aggregation expression. Query predicates such as { field: null }, $exists, and $type have their own matching rules.