Remove by _id in MongoDB console

Typo Johnson picture Typo Johnson · Feb 8, 2011 · Viewed 181.9k times · Source

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

Answer

Nic Cottrell picture Nic Cottrell · Apr 14, 2012

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.