How to remove a field completely from a MongoDB document?



You can use $unset operator to remove a field completely from a MongoDb document. The syntax is as follows:

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

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

> db.removeFieldCompletlyDemo.insertOne({"StudentName":"Larry","StudentFavouriteSubject": ["Java","C","C++","Python"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c6ef55a6fd07954a48906a3") } > db.removeFieldCompletlyDemo.insertOne({"StudentName":"Mike","StudentFavouriteSubject": ["Javascript","HTML5","CSS3"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c6ef57b6fd07954a48906a4") } > db.removeFieldCompletlyDemo.insertOne({"StudentName":"Sam","StudentFavouriteSubject": ["MongoDB","MySQL","SQL Server"]}); {    "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"    ] }

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 })

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" }
Updated on: 2019-07-30T22:30:25+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements