MongoDB Delete Multiple Documents Using MongoDB Shell (original) (raw)
Last Updated : 31 Jan, 2025
MongoDB provides powerful and flexible methods for managing data, including the ability to **delete multiple documents efficiently. The db.collection.deleteMany()
method allows users to remove multiple documents that match a specified filter, making it an essential tool for **database maintenance and **data manipulation.
In this article, we will cover everything you need to know about deleting multiple documents in MongoDB, from **basic syntax to **advanced filtering techniques. This guide is structured to help us understand **how to use deleteMany()
effectively, its **performance implications, and **best practices to ensure smooth database operations
**What is deleteMany()
in MongoDB?
The **db.collection.deleteMany() method is used to **delete multiple documents from a collection that match a specified filter in **Mongo Shell. Unlike deleteOne()
, which removes only a single document, deleteMany()
can remove multiple documents at once, making it ideal for bulk deletions. This method can be used in **multi-document transactions. If we use this method in a capped collection, then it will throw an **exception.
**Key Features of deleteMany()
- Deletes multiple documents that match a specified filter.
- Returns a result containing the number of deleted documents.
- Cannot be used on **capped collections.
- Supports **write concern and **collation options.
**Syntax
**db.collection.deleteMany(
,
{
writeConcern: ,
collation:
}
)
**1. Parameters
- **filter: First parameter of this method which Specifies the selection criteria for deletion using query operators. If an **empty document
{}
is passed, all documents in the collection will be deleted.
**2. Optional Parameters:
- **writeConcern: It Defines the write concern level for the operation
- **collation: It specifies the use of the collation for operations. It Allows specifying language-specific string comparison rules (useful for case-insensitive or locale-based matching).
**3. Return:
The method returns a document containing:
acknowledged
–true
if the write concern is enabled,false
otherwise.deletedCount
– The total number of documents deleted.
**Example 1: Deleting Documents That Match a Filter
We have a MongoDB **database named GeeksforGeeks
, which contains a **collection called contributors
. This collection stores details about contributors in the form of documents with the following structure:
- **Database: GeeksforGeeks
- **Collection: contributor
- **Document: four documents that contain the details of the contributors in the form of field-value pairs.
**Sample Documents in contributors
Collection:
In this example, we are deleting multiple documents from the contributor collection that match the filter, i.e., language: “C#”.
**Query: Delete all contributors who use C#
db.contributors.deleteMany({ language: "C#" });
**Output:
**Explanation:
- The query
{ language: "C#" }
matches **two documents. - Both matching documents are deleted.
- The operation returns
deletedCount: 2
, confirming that two documents were removed successfully.
**Example 2: Deleting All Documents in a Collection
In this example, we are deleting all the documents from the contributor collection by passing empty documents in the **db.collection.deleteMany() method.
**Query: Delete all documents from contributors
collection
db.contributor.deleteMany({})
**Output
**Explanation:
- Since the filter is
{}
, it matches **all documents. - Every document in the
contributors
collection is deleted. - The output confirms the number of deleted documents.
**Warning: This operation **removes all documents **permanently. If you need to clear a collection but keep its structure, use deleteMany({})
instead of drop()
, which removes the collection entirely.
**Example 3: Using Query Operators with deleteMany()
We can use **query operators to refine deletions. Let’s delete all contributors whose _id
is greater than 2.
**Query: Delete contributors with _id
greater than 2
db.contributors.deleteMany({ _id: { $gt: 2 } });
**Output:
{ "acknowledged" : true, "deletedCount" : 2 }
**Explanation:
- The condition
{ _id: { $gt: 2 } }
selects documents where_id
is greater than 2. - Two matching documents are found and deleted.
- The operation confirms deletion with
deletedCount: 2
.
**Best Practices for Using deleteMany()
in MongoDB
When using the deleteMany()
method in MongoDB, it’s crucial to ensure that only the intended documents are removed to prevent accidental data loss. Implementing best practices can help maintain data integrity and improve query efficiency.
**1. Always Use a Filter
- If you don’t provide a filter, all documents will be deleted.
- Example of an unsafe query:
db.users.deleteMany({}); // Deletes ALL users!
**2. Use Indexes for Faster Deletion
- If you’re deleting based on a field like
userID
, ensure an index exists to speed up deletion.
**3. Test Queries Before Executing
- Run a **find query first to verify the documents before deleting:
db.contributors.find({ language: "C#" });
- Then execute
deleteMany()
only when sure.
**4. Consider Write Concern for Critical Operations
- Specify a write concern to ensure data consistency.
- Example:
db.orders.deleteMany({ status: "Cancelled" }, { writeConcern: { w: "majority" } });
**5. Use Collation for Case-Insensitive Deletion
- To perform case-insensitive deletions:
db.users.deleteMany(
{ name: "john doe" },
{ collation: { locale: "en", strength: 2 } }
);
Conclusion
The deleteMany()
method is an essential tool in MongoDB for **bulk deletion of documents based on various filters. Understanding its **syntax, **behavior, and best practices helps in efficiently managing databases without accidental data loss. By following **optimized query patterns, utilizing **indexes, and **testing queries before execution, you can ensure safe and effective deletions in MongoDB. With these examples and techniques, you now have a **comprehensive understanding of how to delete multiple documents using MongoDB Shell