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.
The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag. deletion criteria − (Optional) deletion criteria according to documents will be removed.
To remove an element from a doubly-nested array in MongoDB document, you can use $pull operator. Now field "UserZipCode": "20010" has been removed from a doubly-nested array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With