
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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.
- Related Questions & Answers
- How to delete documents from a collection in MongoDB?
- How to retrieve all the documents from a MongoDB collection using Java?
- Fetching all documents from MongoDB Collection in a beautified form
- How to retrieve documents from a collection in MongoDB?
- How to delete multiple documents from a collection using Java?
- Display only a single field from all the documents in a MongoDB collection
- How to remove all documents from a collection except a single document in MongoDB?
- How to add a new field to all the documents in a MongoDB collection
- How to sum the value of a key across all documents in a MongoDB collection?
- Delete a collection from MongoDB with special characters?
- How to delete document from a collection in MongoDB using deleteOne() method?
- How to count the number of documents in a MongoDB collection?
- Get the maximum mark records from a collection with documents in MongoDB
- Find a value in lowercase from a MongoDB collection with documents
- Find all duplicate documents in a MongoDB collection by a key field?
Advertisements