Open In App

Delete Single Document in MongoDB Using MongoShell

Last Updated : 28 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

What is the 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:

db.collection.deleteOne(
<filter>,
{
writeConcern: <document>,
collation: <document>,
hint: <document|string> // Available starting in MongoDB 4.4
}
)

Key Terms:

  • 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.

Return Value

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).

Examples: Deleting Single Document in MongoDB

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:

  • Database: GeeksforGeeks
  • Collection: contributor
  • Document: four documents that contain the details of the contributors in the form of field-value pairs.

original database and collection

Example 1: Deleting the First Document in a Collection

In this example, we are deleting first document from the contributor collection using an empty filter {}:

Query:

db.contributor.deleteOne({})

Output:

mongodb delete first document from collection example output

Explanation: This will remove the first document in the contributor collection, irrespective of its content.

Example 2: Deleting a Document That Matches a Filter

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:

mongodb delete single document that matches filter example output

Explanation: This will remove the first document in the contributor collection where the name field is “Somya

Example 3: Deleting One Document When Multiple Documents Match the Filter

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:

mongodb delete single document when multiple documents match filter example output

Explanation: In this case, if there are two documents with language: "C#", only the first one will be deleted.

Example 4: Using Collation for String Comparison

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

Example 5: Specifying a Hint for Index Optimization

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.

Common Errors and How to Avoid Them

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.

1. Using deleteOne on a Capped Collection

Error: “cannot remove from a capped collection”

Solution:

  • Ensure the collection is not capped by checking its properties:
db.collection.stats()
  • If the collection is capped and deletions are necessary, consider converting it to an uncapped collection by creating a new uncapped collection and copying the data over.

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 Documents

Issue: Using an overly broad filter can lead to unintended deletions.

Solution:

  • Always test the filter by using findOne or find before performing the deletion:
db.collection.findOne({ filter })
  • This ensures that only the intended document matches the criteria.

Explanation: If the filter criteria are too general or incorrect, deleteOne might delete a document you did not intend to remove.

3. Performance Issues with Large Collections

Issue: Deleting a document in a large collection without an index can be slow, as MongoDB must perform a full collection scan.

Solution:

  • Ensure that the field used in the filter has an index. For example:
db.collection.createIndex({ fieldName: 1 })
  • This improves query performance and reduces the time required for the deleteOne operation.

Explanation: Without an index, MongoDB will examine every document in the collection to find matches, resulting in slower performance.

Important Points for Using deleteOne

  1. Always Use Specific Filters: Avoid using empty filters ({}) unless intentionally deleting the first document in the collection.
  2. Test with Find First: Use findOne with the same filter to ensure that the document you intend to delete matches the criteria.
  3. Index Your Collections: Create indexes on fields commonly used in filters to enhance performance.
  4. Enable Write Concern: Use custom write concerns for critical operations to ensure proper acknowledgment of the operation.

Conclusion

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.

FAQs

How do I delete one document in MongoDB?

Use db.collection.deleteOne({ filter }) in the MongoDB shell or driver to delete a single document matching the filter.

How to delete a single document in Mongoose?

Use Model.deleteOne({ filter }) or Model.findOneAndDelete({ filter }) in Mongoose to delete a single document.

How do I delete one document?

Use the deleteOne method in the appropriate database library with a filter to remove the desired document



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg