How to delete document by _id using MongoDB?



To delete by _id, use remove() in MongoDB. Following is the syntax −

db.yourCollectionName.remove({_id:yourObjectId});

To understand the above syntax, let us create a collection with documents −

> db.demo518.insertOne({"ClientName":"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e88b02db3fbf26334ef610e")
}
> db.demo518.insertOne({"ClientName":"Bob"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e88b030b3fbf26334ef610f")
}
> db.demo518.insertOne({"ClientName":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e88b035b3fbf26334ef6110")
}

Display all documents from a collection with the help of find() method −

> db.demo518.find();

This will produce the following output −

{ "_id" : ObjectId("5e88b02db3fbf26334ef610e"), "ClientName" : "Chris" }
{ "_id" : ObjectId("5e88b030b3fbf26334ef610f"), "ClientName" : "Bob" }
{ "_id" : ObjectId("5e88b035b3fbf26334ef6110"), "ClientName" : "David" }

Following is the query to delete by _id −

> db.demo518.remove({_id:ObjectId("5e88b02db3fbf26334ef610e")});
WriteResult({ "nRemoved" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo518.find();

This will produce the following output −

{ "_id" : ObjectId("5e88b030b3fbf26334ef610f"), "ClientName" : "Bob" }
{ "_id" : ObjectId("5e88b035b3fbf26334ef6110"), "ClientName" : "David" }

Advertisements