MongoDB - Delete Multiple Documents Using MongoDB Shell
The deleteMany() method in MongoDB is used to remove all documents from a collection that match a specified filter. It is ideal for bulk deletions, supports multi-document transactions, and ensures efficient data management.
Features
- 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(
<filter>,
{
writeConcern: <document>,
collation: <document>
}
)
In the above syntax
- filter: Selection criteria for deletion; {} deletes all documents.
- writeConcern: Sets the write concern level for the operation.
- collation: Defines language-specific rules for string comparison.
- 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 } }
);