$ifNull
The $ifNull operator is used to return a specified value if the input expression evaluates to null or undefined. This operator can be useful in scenarios where you want to provide a default value or handle null/undefined cases.
Parameters
-
expression: The expression to evaluate. -
replacement: The value to return if the<expression>evaluates to null or undefined.
Example (MongoDB Shell)
The following example demonstrates the usage of the $ifNull operator to provide a default value when the name field is null or undefined.
Create sample documents
db.users.insertMany([ { _id: 1, name: "John" }, { _id: 2, name: null }, { _id: 3 } ]);
Query example
db.users.aggregate([ { $project: { _id: 1, name: { $ifNull: ["$name", "No Name"] } } } ]);
Output
[
{ "_id": 1, "name": "John" },
{ "_id": 2, "name": "No Name" },
{ "_id": 3, "name": "No Name" }
]
Code examples
To view a code example for using the $ifNull command, choose the tab for the language that you want to use: