P K
P K

Reputation: 10210

How to remove document on the basis of _id?

I tried to delete a document using db.users.remove({_id: "4f6f244f6f35438788aa138f"}) but this commmand doesn't delete anything.

> // myobject is some document that is in our db.things collection
> db.things.remove({_id: myobject._id});

I am unable to figure out ' what is myobject ?' in mongodb documentation.

> db.users.find()

{ "_id" : ObjectId("4f6cd2cb7156522f4f45b26d"), "name" : "james", "age" : 23, 
 "hobbies" : [ "cycling", "painting" ] }
{ "_id" : ObjectId("4f6cd3017156522f4f45b26e"), "name" : "john", "age" : 30 }
{ "_id" : ObjectId("4f6f244f6f35438788aa138f"), "name" : "john" }
{ "_id" : ObjectId("4f6f24556f35438788aa1390"), "name" : "john" }

> db.users.remove({_id: "4f6f244f6f35438788aa138f"})

Upvotes: 16

Views: 17116

Answers (1)

Blacksad
Blacksad

Reputation: 15412

Did you try

db.things.remove({_id: ObjectId("4f6f244f6f35438788aa138f")});

You must pass an ObjectId, not a string.

Upvotes: 31

Related Questions