 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use $ifNull with MongoDB aggregation?
The $ifNull evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value.
Let us first create a collection with documents −
> db.demo372.insertOne({"FirstName":"Chris"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e591aea2ae06a1609a00af6") } > db.demo372.insertOne({"FirstName":null}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e591aef2ae06a1609a00af7") } > db.demo372.insertOne({"FirstName":"David"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e591af42ae06a1609a00af8") } > db.demo372.insertOne({"FirstName":null}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e591afb2ae06a1609a00af9") } Display all documents from a collection with the help of find() method −
> db.demo372.find();
This will produce the following output −
{ "_id" : ObjectId("5e591aea2ae06a1609a00af6"), "FirstName" : "Chris" } { "_id" : ObjectId("5e591aef2ae06a1609a00af7"), "FirstName" : null } { "_id" : ObjectId("5e591af42ae06a1609a00af8"), "FirstName" : "David" } { "_id" : ObjectId("5e591afb2ae06a1609a00af9"), "FirstName" : null } Following is the query to use $ifNull with aggregation−
> db.demo372.aggregate( ...    [ ...       { ...          $project: { ... ...             FirstName: { $ifNull: [ "$FirstName", "NOT PROVIDED" ] } ...          } ...       } ...    ] ... ) This will produce the following output −
{ "_id" : ObjectId("5e591aea2ae06a1609a00af6"), "FirstName" : "Chris" } { "_id" : ObjectId("5e591aef2ae06a1609a00af7"), "FirstName" : "NOT PROVIDED" } { "_id" : ObjectId("5e591af42ae06a1609a00af8"), "FirstName" : "David" } { "_id" : ObjectId("5e591afb2ae06a1609a00af9"), "FirstName" : "NOT PROVIDED" }Advertisements
 