When working with MongoDB database, you may come across instances where you need to remove all the documents in a given collection while preserving the collection. This removes the need to re-create the collection should you need it.
In this post, you will learn how you can remove all the documents from a given collection using the MongoDB built-in commands.
Let’s delve in.
MongoDB Delete All Collections Using DeleteMany() Method
MongoDB provides us with the deleteMany() method that allows us to remove all the documents in a given collection.
The syntax is as shown:
The method accepts a filter as the parameter which allows you to remove any documents that match a specific filter.
Since our goal is to remove all the documents in the collection, we can pass an empty filter as the parameter which clears all the documents.
Let us illustrate.
We start by adding a sample data into the products collection as shown:
[
{ "item": "product1", "qty": 25, "price": 100 "status": "In Stock" },
{ "item": "product_2", "qty": 50, "price": 300 "status": "In Stock" },
{ "item": "product_3", "qty": 170, "price": 450, "status": "In Stock" },
{ "item": "product_4", "qty": 75, "price": 560, "status": "Out of Stock" },
{ "item": "product_5", "qty": 45, "price": 300, "status": "Out of Stock" }
]);
The given commands should insert the documents into the products collection.
To remove the documents in the collection, start by switching to the target database. In our case, we can run the following command:
Once in the target database, we can remove the documents from the products collection as shown in the following command:
The previous command selects all the documents using an empty filter from the products collection and passes them to the deleteMany() method. This should clear all the documents from the document and return an output as shown:
MongoDB Remove All Documents from a Collection Using the Remove() Method
Another method that we can use to remove the documents from a collection is the remove() method.
The command syntax is as shown in the following:
,
)
The method accepts the document query as the parameter. Similarly, we can pass an empty query which allows us to select all the documents in the collection.
An example command is as shown:
The previous method should remove all the documents from the specified collection. Keep in mind that this method is deprecated in the recent MongoDB version. It is recommended to use the deleteMany() method when removing the documents from a collection.
Conclusion
In this article, we explored two main methods of remove all documents from a MongDB collection using the MongoDB Shell commands.
Happy coding!