MongoDB with drivers
This page documents a mongosh method. To see the equivalent
method in a MongoDB driver, see the corresponding page for your
programming language:
Definition
db.collection.deleteMany()Removes all documents that match the
filterfrom a collection.Returns: A document containing: A boolean
acknowledgedastrueif the operation ran with write concern orfalseif write concern was disableddeletedCountcontaining the number of deleted documents
Note
If you are deleting all documents in a large collection, it may be faster to drop the collection and recreate it. Before dropping the collection, note all indexes on the collection. You must recreate any indexes that existed in the original collection. If the original collection was sharded, you must also shard the recreated collection.
For more information on dropping a collection, see
db.collection.drop().
Compatibility
This method is available in deployments hosted in the following environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
Note
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Syntax
The deleteMany() method has the following
syntax:
db.collection.deleteMany( <filter>, { writeConcern: <document>, collation: <document>, hint: <document>|<string>, maxTimeMS: <int>, let: <document> } )
Parameter | Type | Description | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
document | Specifies deletion criteria using query operators. To delete all documents in a collection, pass in an empty
document ( | |||||||||||
document | Optional. A document expressing the write concern. Omit to use the default write concern. 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. | |||||||||||
document | Optional. Specifies the collation to use for the operation. Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. The collation option has the following syntax: When specifying collation, the If the collation is unspecified but the collection has a
default collation (see If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons. You cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort. | |||||||||||
document | Optional. A document or string that specifies the index to use to support the query predicate. The option can take an index specification document or the index name string. If you specify an index that does not exist, the operation errors. For an example, see Specify | |||||||||||
integer | Optional. Specifies the time limit in milliseconds for the delete operation to run before timing out. | |||||||||||
Document | Optional. Specifies a document with a list of variables. This allows you to improve command readability by separating the variables from the query text. The document syntax is: The variable is set to the value returned by the expression, and cannot be changed afterwards. To access the value of a variable in the command, use the double
dollar sign prefix ( To use a variable to filter results, you must access the variable
within the For a complete example using |
Behavior
Sharded Collections
If
deleteMany()is run outside a transaction, operations that target more than one shard broadcast the operation to all shards in the cluster.If
deleteMany()is run inside a transaction, operations that target more than one shard only target the relevant shards.
Warning
Due to concurrent chunk migrations, deleteMany() might run without deleting all
documents that match the specified filter. To ensure you delete all matching
documents, perform one of the following operations:
Run the
deleteMany()method iteratively until the corresponding find query with the same filter returns no documents.Run
deleteMany()within a transaction.Schedule the balancing window so chunk migrations only occur at specific times, and run any
deleteMany()operations outside of the specified window.
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.
Important
In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed transactions should not be a replacement for effective schema design. For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. That is, for many scenarios, modeling your data appropriately will minimize the need for distributed transactions.
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.
Primary Node Failure
db.collection.deleteMany() deletes documents one at a time.
If the primary node fails during a db.collection.deleteMany()
operation, documents that were not yet deleted from secondary nodes are
not deleted from the collection.
Oplog Entries
If a db.collection.deleteMany() operation successfully deletes one
or more documents, the operation adds an entry for each deleted document
on the oplog (operations log). If the operation fails or does
not find any documents to delete, the operation does not add an entry on
the oplog.
Examples
The examples on this page use data from the sample_mflix sample dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the sample dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
Delete Multiple Documents
The following operation deletes all documents where
year is earlier than 1910:
db.movies.deleteMany( { "year": { $lt: 1910 } } )
{ acknowledged: true, deletedCount: 4 }
Similarly, this operation deletes all documents where rated
equals "G" and year is earlier than 1950:
db.movies.deleteMany( { "rated": "G", "year": { $lt: 1950 } } )
{ acknowledged: true, deletedCount: 9 }
deleteMany() with a Timeout and Query Variables
The following operation deletes all documents where year is earlier than the
cutoffYear variable. The example also sets a time limit of 3 seconds:
db.movies.deleteMany( { $expr: { $lt: [ "$year", "$$cutoffYear" ] } }, { let: { cutoffYear: 1910 }, maxTimeMS: 3000 } )
{ acknowledged: true, deletedCount: 4 }
deleteMany() with Write Concern
Given a three member replica set, the following operation specifies a
w of majority and wtimeout of 100:
db.movies.deleteMany( { "rated": "G", "year": { $lt: 1950 } }, { writeConcern: { w: "majority", wtimeout: 100 } } )
{ acknowledged: true, deletedCount: 9 }
If the acknowledgment takes longer than the wtimeout limit, MongoDB throws a
write concern error.
Specify Collation
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
The following operation uses the collation option with
English locale and strength: 2. The filter rated: "g" matches documents
with rated: "G" stored in the collection:
db.movies.deleteMany( { rated: "g", year: { $lt: 1950 } }, { collation: { locale: "en", strength: 2 } } )
{ acknowledged: true, deletedCount: 9 }
Specify hint for Delete Operations
Create indexes on the rated and metacritic fields:
db.movies.createIndex( { rated: 1 } ) db.movies.createIndex( { metacritic: 1 } )
The following delete operation explicitly hints to use the index
{ rated: 1 }:
db.movies.deleteMany( { "metacritic": { $lte: 15 }, "rated": "PG" }, { hint: { rated: 1 } } )
{ acknowledged: true, deletedCount: 7 }
Note
If you specify an index that does not exist, the operation errors.
To view the indexes used, you can use the $indexStats
pipeline:
db.movies.aggregate( [ { $indexStats: { } }, { $sort: { name: 1 } } ] )
The accesses.ops field in the $indexStats output
indicates the number of operations that used the index.