![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to delete all the documents from a collection in MongoDB?
If you want to delete all documents from the collection, you can use deleteMany(). Let us first create a collection and insert some documents to it:
> db.deleteDocumentsDemo.insert({"Name":"Larry","Age":23}); WriteResult({ "nInserted" : 1 }) > db.deleteDocumentsDemo.insert({"Name":"Mike","Age":21}); WriteResult({ "nInserted" : 1 }) > db.deleteDocumentsDemo.insert({"Name":"Sam","Age":24}); WriteResult({ "nInserted" : 1 })
Now display all the documents from the collection. The query is as follows:
> db.deleteDocumentsDemo.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6ab0e064f3d70fcc914805"), "Name" : "Larry", "Age" : 23 } { "_id" : ObjectId("5c6ab0ef64f3d70fcc914806"), "Name" : "Mike", "Age" : 21 } { "_id" : ObjectId("5c6ab0f864f3d70fcc914807"), "Name" : "Sam", "Age" : 24 }
The query is as follows:
> db.deleteDocumentsDemo.deleteMany({});
The following is the output:
{ "acknowledged" : true, "deletedCount" : 3 }
Look at the above sample output. Right now, we do not have any documents in the collection ‘deleteDocumentsDemo’ i.e. we have successfully deleted all the documents using the deleteMany() method.
Advertisements