Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to use $ifNull with MongoDB aggregation?
The $ifNull operator evaluates an expression and returns the value of the expression if it evaluates to a non-null value. If the expression is null or missing, it returns a specified default value.
Syntax
{
$ifNull: [ <expression>, <replacement-expression-if-null> ]
}
Sample Data
Let us create a collection with documents containing null values ?
db.demo372.insertMany([
{ "FirstName": "Chris" },
{ "FirstName": null },
{ "FirstName": "David" },
{ "FirstName": null }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e591aea2ae06a1609a00af6"),
ObjectId("5e591aef2ae06a1609a00af7"),
ObjectId("5e591af42ae06a1609a00af8"),
ObjectId("5e591afb2ae06a1609a00af9")
]
}
Display all documents from the collection ?
db.demo372.find();
{ "_id": ObjectId("5e591aea2ae06a1609a00af6"), "FirstName": "Chris" }
{ "_id": ObjectId("5e591aef2ae06a1609a00af7"), "FirstName": null }
{ "_id": ObjectId("5e591af42ae06a1609a00af8"), "FirstName": "David" }
{ "_id": ObjectId("5e591afb2ae06a1609a00af9"), "FirstName": null }
Example: Replace Null Values
Use $ifNull to replace null FirstName values with "NOT PROVIDED" ?
db.demo372.aggregate([
{
$project: {
FirstName: { $ifNull: [ "$FirstName", "NOT PROVIDED" ] }
}
}
]);
{ "_id": ObjectId("5e591aea2ae06a1609a00af6"), "FirstName": "Chris" }
{ "_id": ObjectId("5e591aef2ae06a1609a00af7"), "FirstName": "NOT PROVIDED" }
{ "_id": ObjectId("5e591af42ae06a1609a00af8"), "FirstName": "David" }
{ "_id": ObjectId("5e591afb2ae06a1609a00af9"), "FirstName": "NOT PROVIDED" }
Key Points
-
$ifNullworks with both null values and missing fields - The replacement value can be a string, number, or any valid expression
- Commonly used in
$projectstages for data transformation
Conclusion
The $ifNull operator is essential for handling null values in MongoDB aggregation pipelines. It provides a clean way to substitute default values for null or missing fields during data processing.
Advertisements
