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" }
Updated on: 2020-04-02T13:00:31+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements