Introduction to MongoDB collection.deleteMany() Method
The deleteMany()
method is a method for deleting multiple documents in MongoDB. It can delete all documents in a collection that meet the specified conditions. Compared with other deletion methods, the deleteMany()
method has the following characteristics:
- It can delete all documents in a collection that meet the specified conditions.
- It can delete documents based on specified conditions.
- It can obtain the result of the deletion operation while deleting documents.
Syntax
The syntax of the deleteMany()
method is as follows:
db.collection.deleteMany(
<filter>,
{
writeConcern: <document>,
collation: <document>
}
)
Here, db.collection
is the collection where the documents to be deleted are located; <filter>
is a document representing the deletion conditions; writeConcern
and collation
are optional parameters.
Use Cases
The deleteMany()
method can be used in the following scenarios:
- Delete all documents in a collection.
- Delete documents in a collection based on specified conditions.
Examples
Here are two examples of the deleteMany()
method.
Example 1
Suppose we have a collection named products
, which stores multiple product information documents. Each document contains fields such as _id
, name
, price
, stock
, and status
. Now, we need to delete all product information documents where the status
field is out_of_stock
. We can use the deleteMany()
method to achieve this. The example code is as follows:
db.products.deleteMany({ status: "out_of_stock" })
After executing the above code, all documents in the products
collection where the status
field is out_of_stock
will be deleted.
Example 2
Suppose we have a collection named orders
, which stores multiple order information documents. Each document contains fields such as _id
, product_id
, user_id
, and quantity
. Now, we need to delete all order information documents where the user_id
field is 1001
. We can use the deleteMany()
method to achieve this. The example code is as follows:
db.orders.deleteMany({ user_id: 1001 })
After executing the above code, all documents in the orders
collection where the user_id
field is 1001
will be deleted.
Conclusion
This article introduces the deleteMany()
method in MongoDB, including syntax, use cases, examples, and conclusions. The deleteMany()
method is a method for deleting multiple documents, which can delete all documents in a collection that meet the specified conditions. It can be used to delete a collection.