Delete documents in collection (table) in mongoDB

You are here : Home / MongoDB Tutorial



Contents of page >


Delete documents (rows) in collection (table) in mongoDB
>
1) Before deleting 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 delete >
> db.employee.find();
{ "_id" : ObjectId("584ebed11127dea5ece72742"), "id" : 1, "firstName" : "ankit" }
{ "_id" : ObjectId("584ebee21127dea5ece72743"), "id" : 2, "firstName" : "sam" }




2) DELETE Example1 in MongoDB >
Let’s DELETE document where id=1 >
We will use remove method of mongoDB.
> db.employee.remove({id:1})
WriteResult({ "nRemoved" : 1 })
>


Let’s understand meaning of statement
WriteResult({ "nRemoved" : 1 })
"nRemoved" : 1 shows that 1 document was deleted.


Now, let's display documents of collection after delete>
> db.employee.find();
{ "_id" : ObjectId("584ebee21127dea5ece72743"), "id" : 2, "firstName" : "sam" }
>
Only 1 document found in collection .


3) DELETE Example2 in MongoDB >
Let’s DELETE document where firstName= "sam" >
> db.employee.remove({firstName:"sam"})
WriteResult({ "nRemoved" : 1 })
>


Now, let's display documents of collection after delete>
> db.employee.find();
>
No document found in collection.


4) How to Delete all documents from employee collection in MongoDB>
> db.employee.remove({});


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


5) SUMMARY>
So in this mongoDB tutorial we learned how to Delete documents in collection (table) in mongoDB.
DELETE Example1 in MongoDB >
Let’s DELETE document where id=1 >
> db.employee.remove({id:1})


DELETE Example2 in MongoDB >
Let’s DELETE document where firstName= "sam" >
> db.employee.remove({firstName:"sam"})


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

Update documents in collection 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 :