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.
- The first parameter is a selection criteria. The type of this parameter is a document.
- The second parameter is optional.
- 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.
- 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.
In the following examples, we are working with:
Document: Four documents contains name and age of the students
- Find and Delete the first document according to the selection criteria:
Here we find and delete the document whose name is Bablue.
- Find and Delete the document according to the selection criteria:
Here, we first sort the documents according to the age field in decreasing order and then delete the first document whose age is 17.
- When no document matches the filter query:
Here, no sumit named document is present in the student collection. So, this method return null.