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 :

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

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.

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

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