w3resource

Detailed Guide to MongoDB db.collection.findOneAndDelete Method


Understanding db.collection.findOneAndDelete() in MongoDB

The db.collection.findOneAndDelete() method in MongoDB finds a single document that matches the filter, deletes it, and returns the deleted document. This is particularly useful when you want to retrieve and remove a document in a single operation, ensuring atomicity.


Syntax:

db.collection.findOneAndDelete(
   <filter>,
   {
     writeConcern: <document>,
     projection: <document>,
     sort: <document>,
     maxTimeMS: <number>,
     collation: <document>
   }
)

Parameters:

Name Type Description
filter Document A query document specifying the criteria for selecting the document to delete.
projection Document (Optional) Specifies the fields to return in the deleted document. Example: { field1: 1, field2: 0 }.
sort Document (Optional) Determines the order in which documents are matched. Example: { age: -1 } to sort by age in descending order.
collation Document (Optional) Allows for locale-specific string comparisons, such as case sensitivity. Example: { locale: "en", strength: 2 }.
hint Document or String (Optional) Specifies the index to use for the operation. Example: { field1: 1 } or "field1_1".

Examples:

Delete a Single Document and Return It

Code:

// Delete a document where 'status' is 'inactive' and return it
db.users.findOneAndDelete(
   { status: "inactive" } // Filter: Match a document with status 'inactive'
)

Explanation:

  • The filter { status: "inactive" } identifies the document to delete.
  • The method deletes the first matching document and returns it.

Delete the Oldest Document Using Sort

Code:

// Delete the oldest document based on 'createdAt' field
db.posts.findOneAndDelete(
   {}, // Filter: Match any document
   {
      sort: { createdAt: 1 } // Sort: Ascending order to get the oldest document
   }
)

Explanation:

  • The empty filter {} matches all documents.
  • Sorting by createdAt: 1 ensures the oldest document is deleted and returned.

Delete a Document with Specific Fields Returned

Code:

// Delete a document and return only selected fields
db.orders.findOneAndDelete(
   { status: "completed" }, // Filter: Match a document with status 'completed'
   {
      projection: { orderId: 1, total: 1 } // Projection: Return only orderId and total fields
   }
)

Explanation:

  • The projection { orderId: 1, total: 1 } ensures only these fields are included in the returned document.

Case-Insensitive Deletion Using Collation

Code:

// Delete a document with case-insensitive comparison
db.products.findOneAndDelete(
   { name: "laptop" }, // Filter: Match a document with name 'laptop'
   {
      collation: { locale: "en", strength: 2 } // Collation: Case-insensitive comparison
   }
)

Explanation:

  • The collation { locale: "en", strength: 2 } ensures "Laptop" and "laptop" are treated as equal during matching.

Optimize the Deletion with Index Hint

Code:

// Use a specific index for the delete operation
db.logs.findOneAndDelete(
   { level: "error" }, // Filter: Match logs with 'error' level
   {
      hint: { level: 1 } // Hint: Use the 'level' index
   }
)

Explanation:

  • The hint parameter specifies the use of the level index to improve the operation's efficiency.

Returned Output

The db.collection.findOneAndDelete() method returns the deleted document if one is found. If no document matches the filter, it returns null.

Example Output

Code:

{
   _id: ObjectId("64f8b0c1e7a8e4d5b8a9d3b1"),
   name: " Anna Apphia",
   status: "inactive"
}

Use Cases

    1. Retrieve and Remove Specific Documents

    • Retrieve a document for processing while ensuring it is removed from the database.

    2. Queue Management

    • Implement a first-in-first-out (FIFO) queue by deleting the oldest document using sort.

    3. Data Cleanup with Immediate Feedback

    • Return deleted records for logging or additional operations.

    4. Language-Specific String Matching

    • Use collation to handle case-insensitive or locale-specific string comparisons..

Error Scenarios

No Matching Documents Found

Code:

db.products.findOneAndDelete(
   { category: "nonexistent" } // Filter: No matching document
)

Output:

null // No document was deleted

Invalid Filter Syntax

Code:

db.users.findOneAndDelete(
   { $unknownOperator: "value" } // Invalid filter
)

Error:

Error: unknown operator $unknownOperator

Solution:

  • Ensure the filter uses valid MongoDB query operators.

Best Practices

    1. Use Specific Filters

    • Avoid broad filters to ensure only the intended document is deleted.

    2. Test Filters Before Deleting

    • Use a find() query to preview the documents that match the filter.

    3. Enable Journaling for Critical Operations

    • Set writeConcern: { j: true } to ensure the deletion is safely logged in the journal.

    4. Optimize Performance with Hints

    • Use the hint parameter for large collections or complex queries.

    5. Leverage Collation for String Matching

    • Apply collation for case-insensitive or language-aware comparisons..

Comparison with Related Methods

Method Description
deleteOne Deletes a single document but does not return the deleted document.
deleteMany Deletes all documents matching the filter but does not return any deleted documents.
findOneAndDelete Deletes a single document matching the filter and returns the deleted document.


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/mongodb/mongodb-db-collection-findoneanddelete.php