The Wayback Machine - https://web.archive.org/web/20250306103428/https://www.geeksforgeeks.org/mongodb-findoneanddelete-method/
Open In App

MongoDB – findOneAndDelete() Method

Last Updated : 22 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The MongoDB findOneAndDelete() is a powerful tool for deleting documents from a collection based on specific criteria. It allows for the deletion of a single document that matches the query filter. In this article, We will learn about MongoDB findOneAndDelete() by understanding various examples and so on.

MongoDB findOneAndDelete()

  • The MongoDB findOneAndDelete() method deletes a single document based on the selection criteria from the collection.
  • It deletes the first document from the collection that matches the given filter query expression.
  • It takes five parameters the first parameter is the selection criteria and the others are optional. 

Syntax:

db.Collection_name.findOneAndDelete(

 Selection_criteria,

{

    projection: <document>,

    sort: <document>,

    maxTimeMS: <number>,

    collation: <document>

})

Parameters:

  • The first parameter is a selection criteria. The type of this parameter is a document.
  • The second parameter is optional.

Optional Parameters:

  • projection: It allows us to select only the necessary data rather than selecting whole data from the document.
  • sort: It specifies the sorting order for the documents matched by the selection criteria. The value 1 sort in increasing order and -1 sort in decreasing order.
  • maxTimeMs: It is the maximum amount of time to allow the query to run.
  • collation: It specifies the use of the collation for operations. This parameter allow us to set rules for how strings are compared such as considering letter case and accent marks. It’s specified as a document.

Return:

  • If a document matches the given filter query then this method returns the deleted document.
  • If no document matches the given filter query then this method return null.

Examples of MongoDB findOneAndDelete()

In the following examples, we are working with:

Database: gfg

Collections: student

Document: Four documents contains name and age of the students

Output:

Example 1: Delete A Document

db.student.findOneAndDelete({name:"Bablue"})

Output:

Output:

Expalnation: This query finds a document in the `student` collection where the `name` is “Bablue”, deletes that document, and returns the deleted document.

Example 2: Find and Delete the document according to the selection criteria

db.student.findOneAndDelete({age:17},{sort:{age:-1}})

Output:

Expalnation: This query finds a document in the `student` collection where the `age` is 17, sorts the matching documents by `age` in descending order, deletes the first document found, and returns the deleted document.

Example 3: When no document matches the filter query:

db.student.findOneAndDelete({name: "Sumit"})

Here, no sumit named document is present in the student collection. So, this method return null.

Output:

example3

Example 4: Delete A Document Using Write Concern

db.student.deleteOne(
{ "_id": ObjectId("601bd3ce0cf217478ba935b2") },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)

Output :

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

Explanation: The deleteOne() method deletes a single document that matches the specified filter. The writeConcern option specifies the level of acknowledgment requested from MongoDB for write operations.

Example 5: Sort And Delete A Document

db.student.find().sort({ "name": 1 }).limit(1).forEach(function(doc) {
db.student.deleteOne({ "_id": doc._id });
});

Output :

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

Explanation: The find().sort().limit().forEach() method chain sorts the documents by name and deletes the first document found.

Example 6: Update Document with Time Limit

MongoDB does not directly support updating a document with a time limit. However, we can achieve similar functionality by updating a document and then setting a TTL (Time-To-Live) index on a date field. This will automatically delete the document after a specified period of time.

For example, to update a document and set a TTL index:

db.student.updateOne(
{ "_id": ObjectId("601bd3ce0cf217478ba935b2") },
{ $set: { "status": "inactive", "expiryDate": new Date(Date.now() + 86400000) } }
);
db.student.createIndex( { "expiryDate": 1 }, { expireAfterSeconds: 0 } )

Output:

{ "n" : 1, "nModified" : 1, "ok" : 1 }

Explanation:In this example, expiryDate is set to be one day from the current date (Date.now() + 86400000 represents milliseconds in a day), and a TTL index is created on expiryDate to automatically delete documents after their expiryDate value.

Conclusion

Overall , MongoDB findOneAndDelete() offers a straightforward approach to deleting documents in MongoDB which making it a valuable tool for managing data in collections. Its ability to delete based on specific criteria and return the deleted document sets as a effective method in MongoDB.

FAQs

What does findOneAndDelete() do?

findOneAndDelete() removes one document from a collection that meets certain conditions and gives back the deleted document.

What parameters does findOneAndDelete() take?

The method takes a selection criteria document as its first parameter and optional parameters such as projection, sort, maxTimeMS, and collation.

Can findOneAndDelete() delete multiple documents?

No, findOneAndDelete() in MongoDB is designed to delete a single document that matches the query criteria.

How does findOneAndDelete() differ from deleteOne()?

findOneAndDelete() returns the deleted document, while deleteOne() does not. Also, deleteOne() deletes a single document matching the filter, while findOneAndDelete() also considers sort order.

Can findOneAndDelete() be used with Write Concern?

Yes, the findOneAndDelete() can be used with Write Concern to determine the level of acknowledgment needed from MongoDB for the delete operation.



Next Article

Similar Reads

three90RightbarBannerImg