• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:9 mins read
You are currently viewing Using $ifNull Operator in MongoDB

The $ifNull operator in MongoDB is used to check if a specified expression is null and returns either the specified expression or a default value. Also, this operator can be very useful when we want to handle null values in MongoDB queries.

Advertisements

Here, we will cover the $ifNull operator of MongoDB with the syntax and some authentic examples.

1. $ifNull Operator Syntax

The syntax for $ifNull in MongoDB is as follows:


# Syntax
{$ifNull: [expression, defaultValue]}

Here,

  • expression: The expression is the value you want to check if it is null.
  • defaultValue:  The defaultValue is the result that will be given if the expression returns null.

2. $ifNull Operator Examples

Let’s take a look at some examples to see how the $ifNull operator works in MongoDB.

Here, we have created a collection WebUser where multiple user information has been inserted. However, some information about the user is not defined or contains null values as seen below.


# Collection created
db.WebUsers.insertMany([
       {
          "_id": 1,
          "FirstName" : "Ian" ,
          "Age": "56",
          "Email": "[email protected]"   
       },
       {
           "_id": 2,
          "FirstName" : "Caroline" ,
          "LastName": null,
          "Age": "41"
       },
       {
           "_id": 3,
          "FirstName" : "Bonnie" ,
          "LastName": "Steve",
          "Age": "34",
          "Email": null
       },
       {
           "_id": 4,
          "FirstName" : "Kai" ,
          "LastName": "Smol",
          "Age": undefined,
          "Email": "[email protected]"
      },
      {
           "_id": 5,
          "FirstName" : "Rose" ,
          "LastName": "Marry",
          "Age": "",
          "Email": "[email protected]"
      }

The output of the MongoDB collection WebUser creation is shown below. Now, we can use the mongoDb $ifNull operator on the documents of this collection to replace the null value with a default value.

mongodb $ifNull operator

2.1 Using $ifNull on null fields

As we can see, the document “1” and “2” has null value against the field LastName in the collection WebUser. If we want to retrieve all the documents and return a default value when the value of LastName field is null.

Furthermore, we applied the mongoDB $ifNull operator and pass the LastName field as the first expression to the $ifNull operator, and the string “LastName is not provided” as the second expression. If the LastName field is null, the mongoDB $ifNull operator will return “LastName is not provided” instead.


# Null fields Example
db.WebUsers.aggregate(
   [
     {
       $project:
          {
            _id: 1,
            FirstName: 1,
            LastName: { $ifNull: [ "$LastName", "LastName is not provided" ] }
          }
     }
   ]
)


The obtained output is:

mongodb $ifNull operator

2.2 Using $ifNull Operator on null and missing fields

The $ifNull operator in MongoDB also takes the missing field as the null. We have document “3” which has the Email field missing. The used $ifNull operator is deployed over the document “2” and “3” as one has the Email field with the null value and the other doesn’t even have the Email field.

Also, if the Email field is missing or null, the default email value “[email protected]” will be set.


# Null and missing fields example
db.WebUsers.aggregate([
     { 
       $match: { _id: { $in: [ 2, 3 ] } } },
     {
       $project:
          {
            _id: 1,
            FirstName: 1,
            LastName: 1,
            Age: 1,
            Email: { $ifNull: [ "$Email", "[email protected]" ] }
          }
     }
])


Look at the output below:

mongodb $ifNull operator

2.3 Using $ifNull Operator on undefined and empty fields

The field with an undefined value is also regarded as null by the $ifNull operator in MongoDB. But, the mongoDB $ifNull operator doesn’t affect the empty field.

Here, we come up with the document “4” and “5” in which one document has the Age field as an undefined value and the second document has the Age field as empty. However, the mongoDB $ifNull operator is operated by specifying these fields with the default string “Age is not given”.


# Undefined and empty fields example
db.WebUsers.aggregate([
     { 
       $match: { _id: { $in: [ 4, 5] } } },
     {
       $project:
          {
            _id: 1,
            FirstName: 1,
            LastName: 1,
            Age: { $ifNull: [ "$Age", "Age is not given" ] }
          }
     }
])


The undefined is replaced by the replacement value, while the empty Age field remains the same in the following output.

mongodb $ifNull operator

2.4 Using $ifNull Operator to update the document with the missing field

Another example is when you want to update a document with a new value only if the current value is null. The mongoDB $ifNull operator is used in the update query for the following example.

Here, the update query specifies updating the document with _id=3. The $set operator is used to set the value of the Email field using $ifNull. If the Email field is null, the value “[email protected]” will be set.


# Update Document Example
db.WebUsers.update(
  { "_id": 3 },
  { $set: { Email: { $ifNull: [ "$Email", "[email protected]" ] } } }
)

Finally, the output from the update query by performing the mongoDB $ifNull operator is as follows:

mongodb $ifNull operator

While the updated document is retrieved from the findOne method:

mongodb $ifNull operator

3. Conclusion

To sum up, the $ifNull operator has advantages for managing null values in queries. It can be applied in several ways, including updating documents with new values, returning a default value under certain conditions, and more.

You can check more details about the $ifNull operator on the official website of MongoDB.