MongoDB – findOneAndDelete() Method
The 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 you 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. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is 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:
In the following examples, we are working with:
Database: gfg
Collections: student
Document: Four documents contains name and age of the students
- Find and Delete the first document according to the selection criteria:
db.student.findOneAndDelete({name:"Bablue"})
Here we find and delete the document whose name is Bablue.
After deletion:
- Find and Delete the document according to the selection criteria:
db.student.findOneAndDelete({age:17},{sort:{age:-1}})
Here, we first sort the documents according to the age field in decreasing order and then delete the first document whose age is 17.
After deletion:
- 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.
Contact Us