Removing empty fields from MongoDB



To remove empty fields, use deleteMany(). Let us first create a collection with documents −

> db.removeEmptyFieldsDemo.insertOne({"StudentName":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce92b9578f00858fb12e919")
}
> db.removeEmptyFieldsDemo.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce92b9878f00858fb12e91a")
}
> db.removeEmptyFieldsDemo.insertOne({"StudentName":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce92b9c78f00858fb12e91b")
}
> db.removeEmptyFieldsDemo.insertOne({"StudentName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce92ba078f00858fb12e91c")
}

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

> db.removeEmptyFieldsDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5ce92b9578f00858fb12e919"), "StudentName" : "" }
{ "_id" : ObjectId("5ce92b9878f00858fb12e91a"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5ce92b9c78f00858fb12e91b"), "StudentName" : "" }
{ "_id" : ObjectId("5ce92ba078f00858fb12e91c"), "StudentName" : "Robert" }

Following is the query to remove empty fields from MongoDB −

> db.removeEmptyFieldsDemo.updateMany({"StudentName": ""}, { $unset : {"StudentName" : 1 }});
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }

Let us check the document once again −

> db.removeEmptyFieldsDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5ce92b9578f00858fb12e919") }
{ "_id" : ObjectId("5ce92b9878f00858fb12e91a"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5ce92b9c78f00858fb12e91b") }
{ "_id" : ObjectId("5ce92ba078f00858fb12e91c"), "StudentName" : "Robert" }

Advertisements