w3resource

Comprehensive Guide to MongoDB db.collection.deleteMany Method


Understanding db.collection.deleteMany() in MongoDB

The db.collection.deleteMany() method is used to delete multiple documents from a MongoDB collection that match a given filter. If no filter is provided, all documents in the collection will be deleted. This method is ideal for batch deletions where multiple records meet specific criteria.


Syntax:

db.collection.deleteMany(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)

Parameters:

Parameter Type Description
filter Document A query document specifying the criteria for documents to delete. To delete all documents, use an empty document {}.
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

Time Series Collections

db.collection.deleteMany() throws a WriteError exception if used on a time series collection. To remove all documents from a time series collection, use db.collection.drop().

Delete a Single Document

To delete a single document, use db.collection.deleteOne() instead.

Alternatively, use a field that is a part of a unique index such as _id.

Transactions

db.collection.deleteMany() can be used inside distributed transactions.

Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern.


Examples:

Delete All Documents Matching a Condition

Code:

// Delete all documents where the 'status' field is 'inactive'
db.users.deleteMany(
   { status: "inactive" } // Filter: Match all documents with status 'inactive'
)

Explanation:

  • The filter { status: "inactive" } matches all documents with the status field set to "inactive".
  • All matching documents are deleted.

Delete All Documents in a Collection

Code:

// Delete all documents from the 'users' collection
db.users.deleteMany({})

Explanation:

  • The empty filter {} selects all documents in the users collection for deletion.
  • Use this operation with caution as it clears the collection.

Delete Documents Using Collation for Case Insensitivity

Code:

// Delete all documents with case-insensitive matching
db.products.deleteMany(
   { category: "electronics" }, // Filter: Match all documents with category 'electronics'
   {
      collation: { locale: "en", strength: 2 } // Collation: Case-insensitive comparison
   }
)

Explanation:

  • The collation { locale: "en", strength: 2 } ensures case-insensitive matching, treating "Electronics" and "electronics" as equal.

Specify Write Concern for the Operation

Code:

// Delete all documents with specific write concern
db.orders.deleteMany(
   { orderStatus: "cancelled" }, // Filter: Match all cancelled orders
   {
      writeConcern: { w: 1, j: true } // WriteConcern: Acknowledge the write and ensure journaling
   }
)

Explanation:

  • The writeConcern parameter ensures that the deletion is acknowledged and journaled.

Delete Documents Using an Index Hint

Code:

// Use a specific index for the delete operation
db.logs.deleteMany(
   { timestamp: { $lt: new Date("2023-01-01") } }, // Filter: Match logs before a specific date
   {
      hint: { timestamp: 1 } // Hint: Use the 'timestamp' index
   }
)

Explanation:

  • The hint parameter specifies the use of the timestamp index to optimize the delete operation.

Returned Output

The db.collection.deleteMany() method returns a document that indicates the outcome of the operation.

{
   acknowledged: true, // Indicates if the write was acknowledged
   deletedCount: 5     // Number of documents deleted
}

Use Cases

    1. Batch Cleanup

    • Remove outdated or invalid records from a collection.

    2. Archival of Data

    • Delete old logs or historical data beyond a certain date range.

    3. Data Reset

    • Clear specific data for reinitialization while retaining the collection structure.

    4. Bulk Operations in Transactions

    • Combine multiple deleteMany operations within a transaction for consistency.

Error Scenarios

No Matching Documents Found

Code:

db.products.deleteMany(
   { category: "nonexistent" } // Filter: No documents match this category
)

Output:

{
   acknowledged: true,
   deletedCount: 0 // No documents were deleted
}

Invalid Filter Syntax

db.users.deleteMany(
   { $invalidOperator: "value" } // Invalid filter
)

Error:

Error: unknown operator $invalidOperator

Solution:

  • Verify the filter syntax and use valid MongoDB query operators.

Best Practices

    1. Use Specific Filters

    • Avoid an empty filter ({}) unless you intend to delete all documents in the collection.

    2. Enable Journaling for Critical Deletions

    • Set writeConcern: { j: true } to ensure the deletion is safely logged in the journal.

    3. Test Filters Before Deleting

    • Use a find() query to preview the documents that match the filter criteria.

    4. Leverage Index Hints for Performance

    • Use the hint parameter to optimize performance for large datasets.

    5. Use Collation for Locale-Specific Matching

    • Apply collation to handle case-insensitive or language-aware comparisons.

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.


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/mongodb-db-collection-deletemany.php