Remove null element from MongoDB array?


You can use $pull operator for this. Let us first create a collection with documents −

> db.removeNullDemo.insertOne(
... {
...    "_id" : 1,
...    "StudentDetails" : [
...       {
...          "FirstName": "John",
...          "LastName":"Smith",
...
...       },
...       {
...          "Age":21
...       },
...       null
...
...    ]
... }
... );
{ "acknowledged" : true, "insertedId" : 1 }
> db.removeNullDemo.insertOne(
... {
...    "_id" : 2,
...    "StudentDetails" : [
...       {
...          "FirstName": "Carol",
...          "LastName":"Taylor",
...
...       },
...       {
...          "Age":23
...       }
...
...
...    ]
... }
... );
{ "acknowledged" : true, "insertedId" : 2 }

Following is the query to display all documents from the collection with the help of find() method −

> db.removeNullDemo.find().pretty();

This will produce the following output −

{
   "_id" : 1,
   "StudentDetails" : [
      {
         "FirstName" : "John",
         "LastName" : "Smith"
      },
      {
         "Age" : 21
      },
      null
   ]
}
{
   "_id" : 2,
   "StudentDetails" : [
      {
         "FirstName" : "Carol",
         "LastName" : "Taylor"
      },
      {
         "Age" : 23
      }
   ]
}

Following is the query to remove null element from MongoDB array −

> db.removeNullDemo.update({_id:1},{$pull:{StudentDetails:null}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the null has been removed or not −

> db.removeNullDemo.find().pretty();

This will produce the following output −

{
   "_id" : 1,
   "StudentDetails" : [
      {
         "FirstName" : "John",
         "LastName" : "Smith"
      },
      {
         "Age" : 21
      }
   ]
}
{
   "_id" : 2,
   "StudentDetails" : [
      {
         "FirstName" : "Carol",
         "LastName" : "Taylor"
      },
      {
         "Age" : 23
      }
   ]
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

791 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements