Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove by _id in MongoDB console

Tags:

mongodb

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

like image 219
Typo Johnson Avatar asked Oct 11 '22 21:10

Typo Johnson


People also ask

How do I remove a field from a collection in MongoDB?

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.

How do I remove all records from a collection in MongoDB?

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.

Can we replace _id in MongoDB?

You cannot update it. You'll have to save the document using a new _id , and then remove the old document.


2 Answers

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.

like image 318
Nic Cottrell Avatar answered Oct 13 '22 09:10

Nic Cottrell


If you would like to remove by a list of IDs this works great.

db.CollectionName.remove({
    "_id": {
        $in: [
            ObjectId("0930292929292929292929"),
            ObjectId("0920292929292929292929")
        ]
     }
}) 
like image 21
mjwrazor Avatar answered Oct 13 '22 11:10

mjwrazor