In this blog post we are going to see how to drop a field from a MongoDb document ?

For people coming from RDBMS you must be remembering the alter table command for dropping/adding columns in a table. In MongoDB it is possible to do this operation on some of the documents (rows) or all documents together. There is no such thing as dropping a column from some rows in RDBMS either you drop it for table or don’t do it at all.

I will be referring to the schema being used in my previous blog post. We added a location field in all documents where name was “Neeraj Bhatt”. Let’s say we want to drop the location field from one document only. This is how we do it :

use school;
switched to db school

db.users.find();
{ "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "28", "location" : "Noida" }
{ "_id" : ObjectId("537d442d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "26", "location" : "Noida" }

We are going to use $unset for dropping the field and below is the example which demonstrates that :

db.users.update({name:'Neeraj Bhatt'},{$unset:{location:""}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

db.users.find();
{ "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "28"}
{ "_id" : ObjectId("537d442d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "26", "location" : "Noida" }

You can see that it only updated one document in above case. Let’s add the location field and try to do an update on all documents.

db.users.update({name:'Neeraj Bhatt'},{$set:{'location':'Delhi'}},{multi:true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

I have intentionally updated location to Delhi for all records here.

db.users.find();
{ "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "28", "location" : "Delhi" }
{ "_id" : ObjectId("537d442d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "26", "location" : "Delhi" }

Now let’s drop the location field from all documents.

db.users.update({name:'Neeraj Bhatt'},{$unset:{location:""}},{multi:true});		
//multi will apply this change on all matching documents
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

db.users.find();
{ "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "28"}
{ "_id" : ObjectId("537d442d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "26"}