Removing empty fields from MongoDB

To remove empty fields from MongoDB documents, use updateMany() with the $unset operator. This operation identifies documents with empty string values and removes those fields entirely.

Syntax

db.collection.updateMany(
    { "fieldName": "" },
    { $unset: { "fieldName": 1 } }
);

Sample Data

Let us create a collection with documents containing empty fields ?

db.removeEmptyFieldsDemo.insertMany([
    { "StudentName": "" },
    { "StudentName": "Chris" },
    { "StudentName": "" },
    { "StudentName": "Robert" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ce92b9578f00858fb12e919"),
        ObjectId("5ce92b9878f00858fb12e91a"),
        ObjectId("5ce92b9c78f00858fb12e91b"),
        ObjectId("5ce92ba078f00858fb12e91c")
    ]
}

View Current Documents

db.removeEmptyFieldsDemo.find();
{ "_id": ObjectId("5ce92b9578f00858fb12e919"), "StudentName": "" }
{ "_id": ObjectId("5ce92b9878f00858fb12e91a"), "StudentName": "Chris" }
{ "_id": ObjectId("5ce92b9c78f00858fb12e91b"), "StudentName": "" }
{ "_id": ObjectId("5ce92ba078f00858fb12e91c"), "StudentName": "Robert" }

Remove Empty Fields

Use updateMany() to remove all empty StudentName fields ?

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

Verify Results

db.removeEmptyFieldsDemo.find();
{ "_id": ObjectId("5ce92b9578f00858fb12e919") }
{ "_id": ObjectId("5ce92b9878f00858fb12e91a"), "StudentName": "Chris" }
{ "_id": ObjectId("5ce92b9c78f00858fb12e91b") }
{ "_id": ObjectId("5ce92ba078f00858fb12e91c"), "StudentName": "Robert" }

Conclusion

The $unset operator with updateMany() effectively removes empty string fields from MongoDB documents. Documents with empty fields will have those fields completely removed, while documents with valid values remain unchanged.

Updated on: 2026-03-15T01:34:10+05:30

541 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements