How to Use findOneAndDelete in MongoDB: Syntax and Examples
Use
findOneAndDelete(filter, options) in MongoDB to find a single document matching the filter and delete it atomically. It returns the deleted document if found, or null if no match exists.Syntax
The findOneAndDelete method takes two main arguments:
- filter: An object specifying the criteria to find the document.
- options (optional): Additional settings like
projectionto specify fields to return, orsortto choose which document to delete if multiple match.
It returns the deleted document or null if no document matches.
mongodb
db.collection.findOneAndDelete(filter, options)Example
This example finds and deletes the first user with the name 'Alice' from the 'users' collection and returns the deleted document.
javascript
const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); try { await client.connect(); const db = client.db('testdb'); const users = db.collection('users'); // Insert sample data await users.insertMany([ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 } ]); // Find and delete one document where name is 'Alice' const result = await users.findOneAndDelete({ name: 'Alice' }); console.log('Deleted document:', result.value); } finally { await client.close(); } } run().catch(console.dir);
Output
Deleted document: { _id: ObjectId("..."), name: 'Alice', age: 25 }
Common Pitfalls
- Not handling the case when no document matches the filter, which returns
nullinresult.value. - Using
findOneAndDeletewithoutawaitor proper promise handling in async code. - Expecting multiple documents to be deleted;
findOneAndDeletedeletes only one document. - Not specifying
sortoption when multiple documents match, which may lead to unexpected document deletion.
javascript
/* Wrong: Not awaiting the async call */ const result = users.findOneAndDelete({ name: 'Alice' }); console.log(result.value); // undefined or Promise object /* Right: Await the async call */ const result = await users.findOneAndDelete({ name: 'Alice' }); console.log(result.value); // deleted document or null
Quick Reference
| Parameter | Description |
|---|---|
| filter | Object to match the document to delete |
| options | Optional settings like projection, sort, maxTimeMS |
| Return | Object with 'value' field containing deleted document or null |
Key Takeaways
Use findOneAndDelete to atomically find and delete a single document matching a filter.
Always await the method in async code to get the deleted document result.
If no document matches, the method returns null in the value field.
Use the sort option to control which document is deleted when multiple match.
findOneAndDelete deletes only one document, not multiple.