How to Delete all documents from collection in MongoDB

You are here : Home / MongoDB Tutorial



Contents of page >
  • 1) Before deleting all documents from collection let’s create and query collection in MongoDB
  • 2) How to Delete all documents (records) from collection in MongoDB>


1) Before deleting all documents from collection let’s create and query collection in MongoDB

Let's create collection and insert documents in it before delete >
> db.employee.insert({id : 1,  firstName:"ankit"})
> db.employee.insert({id : 2,  firstName:"sam"})
First line above will create table (or collection) (if table already exists it will insert documents in it).

Let's query/see what is there in collection before deleting all documents >
> db.employee.find();
{ "_id" : ObjectId("584ebed11127dea5ece72742"), "id" : 1, "firstName" : "ankit" }
{ "_id" : ObjectId("584ebee21127dea5ece72743"), "id" : 2, "firstName" : "sam" }


2) How to Delete all documents (records) from collection in MongoDB>

Here we delete all documents from collection employee

db.employee.remove({});


Let's query/see what is there in collection after deleting all documents >
> db.employee.find();
No, document was found.



SUMMARY>
So in this mongoDB tutorial we learned how to Delete all documents from collection in mongoDB.
Delete all documents from employee collection in MongoDB>
> db.employee.remove({});



Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>

What is MongoDB - A quick introduction to database

objectId in MongoDB

Create new database in mongoDB

Create new collection(table) in mongoDB

Data Modelling in MongoDB - Multiple tables


Labels: MongoDB
eEdit
Must read for you :