MongoDB db.collection.deleteOne Method Explained with Examples
Understanding db.collection.deleteOne() in MongoDB
The db.collection.deleteOne() method in MongoDB is used to delete a single document from a collection. It identifies the document to delete based on a specified filter. If multiple documents match the filter, only the first document encountered in the natural order of the collection is deleted.
This method is commonly used when you need to remove a specific document from a collection without affecting others.
Syntax:
db.collection.deleteOne( <filter>, { writeConcern: <document>, collation: <document>, hint: <document|string> } )
Parameters:
Name | Type | Description |
---|---|---|
filter | Document | A query document that specifies the criteria for selecting the document to delete. |
writeConcern | Document (Optional) | Specifies the level of acknowledgment requested from the server for the write operation. Example: { w: 1, j: true }. |
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 delete operation. Example: { field1: 1 } or "field1_1". |
Behavior:
Deletion Order
db.collection.deleteOne() deletes the first document that matches the filter. Use a field that is part of a unique index such as _id for precise deletions.
Sharded Collections
To use db.collection.deleteOne() on a sharded collection:
- If you only target one shard, you can use a partial shard key in the query specification or,
- If you set limit: 1, you do not need to provide the shard key or _id field in the query specification.
Transactions
db.collection.deleteOne() can be used inside distributed transactions.
Examples
Delete a Single Document Matching a Condition
Code:
// Delete a document where the 'status' field is 'inactive'
db.users.deleteOne(
{ status: "inactive" } // Filter: Find the first document with status 'inactive'
)
Explanation:
- The filter { status: "inactive" } matches documents where the status field is "inactive".
- Only the first matching document is deleted.
Delete a Document with Case-Insensitive Collation
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 collation { locale: "en", strength: 2 } ensures that "Teal" and "teal" are treated as equivalent during the match.
Delete a Document Using a Specific Index
Code:
// Delete a document using a specific index
db.users.deleteOne(
{ age: { $gte: 50 } }, // Filter: Match documents with age greater than or equal to 50
{
hint: { age: 1 } // Hint: Use the 'age' index for efficient deletion
}
)
Explanation:
- The hint parameter specifies the use of the age index to optimize the delete operation.
Specify Write Concern for the Operation
Code:
// Delete a document with specific write concern
db.users.deleteOne(
{ email: "[email protected]" }, // Filter: Match document with the given email
{
writeConcern: { w: 1, j: true } // WriteConcern: Acknowledge the write and ensure journaling
}
)
Explanation:
- The writeConcern parameter ensures that the deletion is acknowledged and journaled before the operation is considered complete.
Returned Output
The db.collection.deleteOne() method returns a document indicating the outcome of the operation.
Code:
{
acknowledged: true, // Indicates if the write was acknowledged
deletedCount: 1 // Number of documents deleted (0 or 1)
}
Use Cases
- Delete a single occurrence of a duplicate record.
- Remove outdated or invalid entries from a collection.
- Use collation for language-aware string matching during deletions.
- Leverage indexes with the hint parameter for efficient deletions.
1. Removing Duplicate Documents
2. Transactional Cleanup
3. Localized String Matching
4. Optimized Deletion
Error Scenarios
No Matching Documents Found
Code:
db.users.deleteOne(
{ username: "nonexistent" } // Filter: No document matches this username
)
Output:
{ acknowledged: true, deletedCount: 0 // No document was deleted }
Invalid Filter Syntax
db.users.deleteOne( { $unknownOperator: "value" } // Invalid filter )
Error:
Error: unknown operator $unknownOperator
Solution:
- Verify the filter syntax and ensure it uses valid MongoDB query operators.
Best Practices
- Avoid using an empty filter ({}), which may delete an unintended document.
- Use a findOne() query to verify the document matches the filter criteria.
- Set writeConcern: { j: true } to ensure the operation is safely logged in the journal.
- Use the hint parameter for large collections to improve query performance.
1. Always Use Specific Filters
2. Test Filters Before Deleting
3. Enable Journaling for Critical Operations
4. Monitor Performance with Hints
Comparison with Related Methods
Method | Description |
---|---|
deleteOne | Deletes a single document matching the filter. |
deleteMany | Deletes all documents matching the filter. |
findOneAndDelete | Finds a single document matching the filter, deletes it, and returns the deleted document. |
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics