How to delete document from a collection in MongoDB using deleteOne() method?


To delete document from a collection in MongoDB, you can use the deleteOne() method. Let us first create a collection and insert some documents to it:

> db.deleteDocumentsDemo.insert({"Name":"Larry","Age":23});
WriteResult({ "nInserted" : 1 })
> db.deleteDocumentsDemo.insert({"Name":"Mike","Age":21});
WriteResult({ "nInserted" : 1 })
> db.deleteDocumentsDemo.insert({"Name":"Sam","Age":24});
WriteResult({ "nInserted" : 1 })

Now display all the documents from the collection. The query is as follows:

> db.deleteDocumentsDemo.find().pretty();

The following is the output:

{
   "_id" : ObjectId("5c6ab0e064f3d70fcc914805"),
   "Name" : "Larry",
   "Age" : 23
}
{
   "_id" : ObjectId("5c6ab0ef64f3d70fcc914806"),
   "Name" : "Mike",
   "Age" : 21
}
{ "_id" : ObjectId("5c6ab0f864f3d70fcc914807"), "Name" : "Sam", "Age" : 24 }

Now use the deleteOne() command. The name suggests that it will delete only one document from collection. The query is as follows:

> db.deleteDocumentsDemo.deleteOne({"Name":"Larry"});

The following is the output:

{ "acknowledged" : true, "deletedCount" : 1 }

Now display the documents from the collection with the help of find() command. The query is as follows:

> db.deleteDocumentsDemo.find().pretty();

The following is the output:

{
   "_id" : ObjectId("5c6ab0ef64f3d70fcc914806"),
   "Name" : "Mike",
   "Age" : 21
}
{ "_id" : ObjectId("5c6ab0f864f3d70fcc914807"), "Name" : "Sam", "Age" : 24 }

Look at the above sample output, there is no document with the field Name: “Larry”.

Updated on: 30-Jul-2019

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements