How to remove a field completely from a MongoDB document?

You can use the $unset operator to remove a field completely from a MongoDB document. The syntax is as follows ?

Syntax

db.yourCollectionName.update({}, {$unset: {yourFieldName:1}}, false, true);

Sample Data

To understand the above syntax, let us create a collection with some documents. The query to create a collection with documents is as follows ?

db.removeFieldCompletlyDemo.insertOne({"StudentName":"Larry","StudentFavouriteSubject":
["Java","C","C++","Python"]});

db.removeFieldCompletlyDemo.insertOne({"StudentName":"Mike","StudentFavouriteSubject":
["Javascript","HTML5","CSS3"]});

db.removeFieldCompletlyDemo.insertOne({"StudentName":"Sam","StudentFavouriteSubject":
["MongoDB","MySQL","SQL Server"]});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c6ef55a6fd07954a48906a3")
}
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c6ef57b6fd07954a48906a4")
}
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c6ef59c6fd07954a48906a5")
}

Display all documents from a collection with the help of find() method. The query is as follows ?

db.removeFieldCompletlyDemo.find().pretty();

The following is the output ?

{
    "_id" : ObjectId("5c6ef55a6fd07954a48906a3"),
    "StudentName" : "Larry",
    "StudentFavouriteSubject" : [
        "Java",
        "C",
        "C++",
        "Python"
    ]
}
{
    "_id" : ObjectId("5c6ef57b6fd07954a48906a4"),
    "StudentName" : "Mike",
    "StudentFavouriteSubject" : [
        "Javascript",
        "HTML5",
        "CSS3"
    ]
}
{
    "_id" : ObjectId("5c6ef59c6fd07954a48906a5"),
    "StudentName" : "Sam",
    "StudentFavouriteSubject" : [
        "MongoDB",
        "MySQL",
        "SQL Server"
    ]
}

Example

Remove field "StudentFavouriteSubject" from documents. The query is as follows ?

db.removeFieldCompletlyDemo.update({}, {$unset: {StudentFavouriteSubject:1}}, false, true);
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

Verify Result

We have removed the field "StudentFavouriteSubject" from documents. Let us now display all documents from a collection to verify. The query is as follows ?

db.removeFieldCompletlyDemo.find().pretty();

The following is the output ?

{ "_id" : ObjectId("5c6ef55a6fd07954a48906a3"), "StudentName" : "Larry" }
{ "_id" : ObjectId("5c6ef57b6fd07954a48906a4"), "StudentName" : "Mike" }
{ "_id" : ObjectId("5c6ef59c6fd07954a48906a5"), "StudentName" : "Sam" }

Conclusion

The $unset operator effectively removes specified fields from all matching documents. Using an empty query filter {} with the multi-update flag ensures the field is removed from all documents in the collection.

Updated on: 2026-03-14T23:50:15+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements