I have added MiddleName attribute to my Customer object. Customer is a simple Object() instance. I want to remove this attribute from my object. How can I do that? I am using MongoDb interactive Console.
1 Answer
You should use the $unset modifier while updating:
To delete: (most recent syntax) https://docs.mongodb.com/manual/reference/method/db.collection.update/
db.collection.update(
{},
{
$unset : {
"properties.service" : 1
}
},
{
multi: true
}
);
Updated thanks to Xavier Guihot comment!
To delete: (only left for reference of the old syntax)
// db.collection.update( criteria, objNew, upsert, multi )
db.collection.update(
{
"properties.service" : {
$exists : true
}
},
{
$unset : {
"properties.service" : 1
}
},
false,
true
);
To verify they have been deleted you can use:
db.collection.find(
{
"properties.service" : {
$exists : true
}
}
).count(true);
Remember to use the multi option as true if you want to update multiple records. In my case I wanted to delete the properties.service attribute from all records on this collection.
4 Comments
Imran Omar Bukhsh
i have run this command on a db of 20million records. Its been 14 minutes already. Deleting one field.
David J.
Yep, I'm not surprised. Can you suggest a better way for a database designed to be schema-free?
spazm
The argument signature for db.collection.update was change in 2.2 : docs.mongodb.org/manual/reference/method/db.collection.update
Xavier Guihot
Note that checking if the field exist is not necessary:
db.collection.update({}, { $unset: { "properties.service": 1 } }, { multi: true })