Clear All Data from a Collection
Sometimes you may need to remove all documents from a collection. MongoDB provides two primary ways to achieve this: using deleteMany({}) to remove all documents, or using drop() to remove the entire collection.
First, let's create a new products collection with some sample data.
db.products.insertMany([
{ name: "Laptop", price: 1000, category: "Electronics" },
{ name: "Smartphone", price: 500, category: "Electronics" },
{ name: "Headphones", price: 100, category: "Electronics" }
]);
Method 1: Remove All Documents with deleteMany()
You can remove all documents from a collection by passing an empty filter {} to the deleteMany() method. This approach deletes the data but preserves the collection itself, including its indexes.
db.products.deleteMany({});
The output shows that all three documents were deleted.
{ "acknowledged": true, "deletedCount": 3 }
You can verify that the collection is now empty by running a find() query.
db.products.find();
This command will return no documents.
Method 2: Drop the Entire Collection with drop()
The drop() method is more destructive. It completely removes the collection, including all its documents, indexes, and associated metadata.
First, let's re-insert the sample data so we have a collection to drop.
db.products.insertMany([
{ name: "Laptop", price: 1000, category: "Electronics" },
{ name: "Smartphone", price: 500, category: "Electronics" },
{ name: "Headphones", price: 100, category: "Electronics" }
]);
Now, drop the products collection entirely.
db.products.drop();
The output true confirms that the collection was successfully dropped.
true
If you now try to query the products collection, it will not return any results because the collection no longer exists.
db.products.find();
This command will produce no output, as the collection is gone. To exit the mongosh shell, you can type exit or press Ctrl+D.