How to Use $ifNull in Aggregation in MongoDB
In MongoDB aggregation, use
$ifNull to replace null or missing values with a specified default. It takes exactly two arguments: the expression to check and the replacement value if the expression is null or missing.Syntax
The $ifNull operator takes exactly two arguments inside an array. The first is the expression to check for null or missing values. The second is the value to use if the first is null or missing.
Syntax pattern:
{ $ifNull: [ <expression>, <replacement> ] }json
{ $ifNull: [ <expression>, <replacement> ] }Example
This example shows how to use $ifNull in an aggregation pipeline to replace null or missing score fields with a default value of 0.
mongodb
db.students.aggregate([
{
$project: {
name: 1,
score: { $ifNull: ["$score", 0] }
}
}
])Output
[
{ "_id" : ObjectId("..."), "name" : "Alice", "score" : 85 },
{ "_id" : ObjectId("..."), "name" : "Bob", "score" : 0 },
{ "_id" : ObjectId("..."), "name" : "Charlie", "score" : 92 }
]
Common Pitfalls
- Using
$ifNullwith only one argument causes an error; it requires exactly two. - It only checks for
nullor missing fields, not other falsy values like0or"". - Confusing
$ifNullwith$coalescewhich handles multiple expressions.
mongodb
/* Wrong usage: missing second argument */ db.collection.aggregate([ { $project: { value: { $ifNull: ["$field"] } } } ]) /* Correct usage: provide replacement value */ db.collection.aggregate([ { $project: { value: { $ifNull: ["$field", "default"] } } } ])
Quick Reference
$ifNull checks if the first expression is null or missing and returns the second expression if true, otherwise returns the first.
- Arguments: exactly two
- Returns: first expression if not null, else second
- Use case: default values in aggregation
| Feature | Description |
|---|---|
| Arguments | Two: expression to check, replacement value |
| Returns | First expression if not null, else replacement |
| Use Case | Provide default values for null or missing fields |
| Error | Throws if less or more than two arguments |
Key Takeaways
Use $ifNull with exactly two arguments: the value to check and the default replacement.
$ifNull returns the replacement only if the first value is null or missing, not for other falsy values.
Common mistake is to omit the replacement argument, which causes errors.
$ifNull is useful in aggregation pipelines to ensure fields have fallback values.
Remember $ifNull differs from $coalesce, which accepts multiple expressions.