How to use deleteOne() function in MongoDB?


The deleteOne() function in MongoDB deletes at most one matching document from a collection. Let us first create a collection with documents −

> db.demo363.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d2c3d0ada61456dc9369")
}
> db.demo363.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d2c7d0ada61456dc936a")
}
> db.demo363.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d2cad0ada61456dc936b")
}
> db.demo363.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d2d1d0ada61456dc936c")
}

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

> db.demo363.find();

This will produce the following output −

{ "_id" : ObjectId("5e57d2c3d0ada61456dc9369"), "Name" : "Chris" }
{ "_id" : ObjectId("5e57d2c7d0ada61456dc936a"), "Name" : "David" }
{ "_id" : ObjectId("5e57d2cad0ada61456dc936b"), "Name" : "Bob" }
{ "_id" : ObjectId("5e57d2d1d0ada61456dc936c"), "Name" : "Chris" }

Following is the query to work with deleteOne() in MongoDB −

> db.demo363.deleteOne({Name:"Chris"});
{ "acknowledged" : true, "deletedCount" : 1 }

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

> db.demo363.find();

This will produce the following output −

{ "_id" : ObjectId("5e57d2c7d0ada61456dc936a"), "Name" : "David" }
{ "_id" : ObjectId("5e57d2cad0ada61456dc936b"), "Name" : "Bob" }
{ "_id" : ObjectId("5e57d2d1d0ada61456dc936c"), "Name" : "Chris" }

Updated on: 02-Apr-2020

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements