What is the difference between deleteOne() and findOneAndDelete() operation in MongoDB?


The findOneAndDelete() deletes single documents from the collection on the basis of a filter and sort criteria as well as it returns the deleted document.

The deleteOne() removes single document from the collection.

Let us see an example and create a collection with documents −

> db.demo448.insertOne({"Name":"Chris","Age":21});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7a291cbbc41e36cc3caeca")
}
> db.demo448.insertOne({"Name":"David","Age":23});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7a2926bbc41e36cc3caecb")
}
> db.demo448.insertOne({"Name":"Bob","Age":22});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7a2930bbc41e36cc3caecc")
}

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

> db.demo448.find();

This will produce the following output −

{ "_id" : ObjectId("5e7a291cbbc41e36cc3caeca"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e7a2926bbc41e36cc3caecb"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e7a2930bbc41e36cc3caecc"), "Name" : "Bob", "Age" : 22 }

Following is the query to implement deleteOne() −

> db.demo448.deleteOne({_id:ObjectId("5e7a2926bbc41e36cc3caecb")});

This will produce the following output −

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

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

> db.demo448.find();

This will produce the following output −

{ "_id" : ObjectId("5e7a291cbbc41e36cc3caeca"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e7a2930bbc41e36cc3caecc"), "Name" : "Bob", "Age" : 22 }

Following is the query to implement findOneAndDelete() −

> db.demo448.findOneAndDelete({"_id":ObjectId("5e7a2930bbc41e36cc3caecc")});

This will produce the following output −

{ "_id" : ObjectId("5e7a2930bbc41e36cc3caecc"), "Name" : "Bob", "Age" : 22 }

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

> db.demo448.find();

This will produce the following output −

{ "_id" : ObjectId("5e7a291cbbc41e36cc3caeca"), "Name" : "Chris", "Age" : 21 }

Updated on: 11-May-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements