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 :
1 2 3 4 5 6 7 8 |
[php] 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" } [/php] |
We are going to use $unset for dropping the field and below is the example which demonstrates that :
1 2 3 4 5 6 7 8 |
[php] 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" } [/php] |
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.
1 2 3 4 |
[php] db.users.update({name:'Neeraj Bhatt'},{$set:{'location':'Delhi'}},{multi:true}); WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 }) [/php] |
I have intentionally updated location to Delhi for all records here.
1 2 3 4 5 |
[php] db.users.find(); { "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "28", "location" : "Delhi" } { "_id" : ObjectId("537d442d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "26", "location" : "Delhi" } [/php] |
Now let’s drop the location field from all documents.
1 2 3 4 5 6 7 8 9 |
[php] 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"} [/php] |
Recent Comments