Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove document on the basis of _id?

Tags:

mongodb

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"})
like image 666
P K Avatar asked Mar 25 '12 14:03

P K


People also ask

Can we override _ID in MongoDB?

The _id field is immutable—that is, once a document exists in your MongoDB system, it has, by definition, been assigned an _id, and you cannot change or update its primary key. That said, _id can be overridden when you insert new documents, but by default it will be populated with an ObjectID.

How do I remove all files 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.

How does the value of _ID get assigned to a document MongoDB?

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. This also applies to documents inserted through update operations with upsert: true.


1 Answers

Did you try

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

You must pass an ObjectId, not a string.

like image 84
Blacksad Avatar answered Oct 14 '22 05:10

Blacksad