In the MongoDB console how can I remove a record by id? Here's my collection :
[
{
"_id" : { "$oid" : "4d512b45cc9374271b02ec4f" },
"name" : "Gazza"
},
{
"_id" : { "$oid" : "4d513345cc9374271b02ec6c" },
"name" : "Dave",
"adminOf" : { },
"email" : "[email protected]"
}
]
And here are the commands I've tried that don't work :
db.test_users.remove( {"_id":{"$oid":new ObjectId("4d512b45cc9374271b02ec4f")}});
db.test_users.remove( {"_id":{"$oid":"4d513345cc9374271b02ec6c"}});
db.test_users.remove( {"_id":"4d512b45cc9374271b02ec4f"});
db.test_users.remove( {"_id":new ObjectId("4d512b45cc9374271b02ec4f")});
Removing by name works :
db.test_users.remove( {"name":"Gazza"});
This is in the browser shell on at mongodb.org if that makes any difference
Thanks
In MongoDB, you can use the $unset field update operator to completely remove a field from a document. The $unset operator is designed specifically to delete a field and its value from the document.
To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.
You cannot update it. You'll have to save the document using a new _id , and then remove the old document.
Very close. This will work:
db.test_users.deleteOne( {"_id": ObjectId("4d512b45cc9374271b02ec4f")});
i.e. you don't need a new for the ObjectId.
Also, note that in some drivers/tools, remove()
is now deprecated and deleteOne
or deleteMany
should be used instead.
If you would like to remove by a list of IDs this works great.
db.CollectionName.remove({
"_id": {
$in: [
ObjectId("0930292929292929292929"),
ObjectId("0920292929292929292929")
]
}
})
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