In the MongoDB console how can I remove a record by id? Here\'s my collection :
[
{
\"_id\" : { \"$oid\" : \"4d512b45cc9374271b02ec4f\" },
\"nam
db.collection("collection_name").deleteOne({_id:ObjectID("4d513345cc9374271b02ec6c")})
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.
Even though this post is outdated, collection.remove is deprecated! collection.delete_one
should be used instead!
More information can be found here under #remove
The answer is that the web console/shell at mongodb.org behaves differently and not as I expected it to. An installed version at home worked perfectly without problem ie; the auto generated _id on the web shell was saved like this :
"_id" : { "$oid" : "4d512b45cc9374271b02ec4f" },
The same document setup at home and the auto generated _id was saved like this :
"_id" : ObjectId("4d5192665777000000005490")
Queries worked against the latter without problem.
I've just bumped into this myself and this variation worked for me:
db.foo.remove({**_id**: new ObjectId("4f872685a64eed5a980ca536")})
If you would like to remove by a list of IDs this works great.
db.CollectionName.remove({
"_id": {
$in: [
ObjectId("0930292929292929292929"),
ObjectId("0920292929292929292929")
]
}
})