0
0
MongoDBquery~5 mins

Delete all documents in collection in MongoDB

Choose your learning style9 modes available
Introduction

Sometimes you want to remove all data from a collection to start fresh or clear old information.

You want to clear all user data before importing new data.
You need to reset a test database collection during development.
You want to delete all logs older than a certain date (after filtering).
You want to empty a collection before archiving it.
You want to remove all temporary data stored in a collection.
Syntax
MongoDB
db.collection.deleteMany({})

The empty curly braces {} mean 'match all documents'.

This command deletes all documents but keeps the collection itself.

Examples
Deletes all documents from the users collection.
MongoDB
db.users.deleteMany({})
Removes all documents from the orders collection.
MongoDB
db.orders.deleteMany({})
Sample Program

This example inserts two products, deletes all products, then shows the empty collection.

MongoDB
use shopDB
 db.products.insertMany([{name: 'Pen', price: 1}, {name: 'Notebook', price: 5}])
 db.products.deleteMany({})
 db.products.find().toArray()
OutputSuccess
Important Notes

Deleting all documents does not delete the collection itself.

Use deleteMany({}) carefully because it removes everything.

Summary

Use deleteMany({}) to remove all documents from a collection.

The collection remains but is empty after deletion.

This is useful for clearing data without dropping the collection.