MongoDB is a NoSQL database that allows developers to perform operations on collections and documents with ease. One such operation is deleting a single document from a collection using the deleteOne
method in MongoShell.
In this article, we will explore the deleteOne
method in detail, covering everything from basic usage to advanced scenarios to help you execute precise deletion operations efficiently.
deleteOne
Method?
The deleteOne
method is used to delete a single document in MongoDB. It removes the first document that matches the specified filter criteria. If multiple documents satisfy the condition, only the first match is deleted. This method can also be used within multi-document transactions, ensuring atomicity and reliability. The deleteOne
method cannot be used on capped collections, as they do not allow deletions. Attempting this will throw an exception.
Syntax:
Key Terms:db.collection.deleteOne(
<filter>,
{
writeConcern: <document>,
collation: <document>,
hint: <document|string> // Available starting in MongoDB 4.4
}
)
filter
: Specifies the selection criteria using query operators. If an empty document {}
is passed, the method will delete the first document in the collection.writeConcern
(optional): Overrides the default write concern. This is useful when you want custom acknowledgment behavior.collation
(optional): Allows language-specific string comparison rules, such as handling case sensitivity or accent marks.hint
(optional): Available from MongoDB 4.4, specifies the index to use for the query, optimizing performance.The deleteOne
method returns a document containing:
acknowledged
: A boolean indicating whether the operation was acknowledged based on the write concern.deletedCount
: The number of documents deleted (should always be 1 if a match is found).Let's look at some examples, that explains how users can delete a single document from a collection in MongoDB. These examples cover different use cases of the deleteOne method to delete single document from a collection.
In the following examples, we are working with:
In this example, we are deleting first document from the contributor collection using an empty filter {}:
Query:
db.contributor.deleteOne({})
Output:
Explanation: This will remove the first document in the contributor
collection, irrespective of its content.
In this example, we are deleting a single document that matches a specific condition, such as deleting a contributor named "Somya" from the contributor collection.
Query:
db.contributor.deleteOne({ name: "Somya" })
Output:
Explanation: This will remove the first document in the contributor
collection where the name
field is "Somya"
In this example, we are deleting a document from the contributor collection. Here two document matches the filter(i.e., language: "C#"), so this method will delete the first document that matches the filter among these two documents.
Query:
db.contributor.deleteOne({ language: "C#" })
Output:
Explanation: In this case, if there are two documents with language: "C#"
, only the first one will be deleted.
To delete a document with case-insensitive matching, you can specify collation:
Query:
db.contributor.deleteOne(
{ name: "somya" },
{ collation: { locale: "en", strength: 2 } }
)
Output:
{
"acknowledged": true,
"deletedCount": 1
}
Explanation: Collation ensures that "Somya" and "somya" are treated as equal for the purposes of the query. The strength: 2
parameter makes the comparison case-insensitive
For collections with large datasets, specifying a hint can improve performance:
Query:
db.contributor.deleteOne(
{ name: "Somya" },
{ hint: "name_index" }
)
Output:
{
"acknowledged": true,
"deletedCount": 1
}
Explanation: This command ensures that MongoDB uses the name_index
index to optimize the query for deleting the document.
When using the deleteOne
method in MongoDB, certain errors can arise due to misconfiguration or improper usage. Understanding these common issues and their solutions can help you avoid unnecessary complications and ensure smooth operations.
deleteOne
on a Capped Collection
Error: "cannot remove from a capped collection"
Solution:
db.collection.stats()
Explanation: Capped collections are fixed-size collections that do not allow deletions. Attempting to delete a document from a capped collection will result in an error.
2. Deleting Unintended DocumentsIssue: Using an overly broad filter can lead to unintended deletions.
Solution:
findOne
or find
before performing the deletion:db.collection.findOne({ filter })
Explanation: If the filter criteria are too general or incorrect, deleteOne
might delete a document you did not intend to remove.
Issue: Deleting a document in a large collection without an index can be slow, as MongoDB must perform a full collection scan.
Solution:
db.collection.createIndex({ fieldName: 1 })
deleteOne
operation.Explanation: Without an index, MongoDB will examine every document in the collection to find matches, resulting in slower performance.
Important Points for UsingdeleteOne
{}
) unless intentionally deleting the first document in the collection.findOne
with the same filter to ensure that the document you intend to delete matches the criteria.The deleteOne
method in MongoDB’s MongoShell is a powerful tool for deleting single documents in a precise and efficient manner. By understanding its syntax, parameters, and return values, developers can avoid common pitfalls and perform reliable operations. Whether we are working with basic or advanced use cases, following the best practices outlined here will ensure successful deletion operations. By mastering the deleteOne
method, you can handle document deletion with confidence and precision, making it a valuable skill for working with MongoDB.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4