MongoDB Delete Document

MongoDB provide remove() method to delete document from collection.


Syntax



>db.Collection_Name.remove(Deletetion_Criteria,1)


Two parameters accepted by the remove() method.
Deletion_Criteria: This optional parameter based on the criteria used to delete documents.
Just One: This optional parameter is used to remove a document put "true" or 1.

Example


Suppose we have an employee collection EMP like below.


{
    "_id" : ObjectId("584a7ec1309356d26bef1772"),
    "Name" : "Vipul",
    "Salary" : 30000.0,
    "Project" : "Codeafri UI",
    "DOJ" : ISODate("2015-11-01T20:19:55.782Z")
}

{
    "_id" : ObjectId("584a7ec1309356d26bef1773"),
    "Name" : "Ashish",
    "Salary" : 100000.0,
    "Project" : "Codeafri Project architect",
    "DOJ" : ISODate("2013-10-01T20:19:55.782Z")
}

{
    "_id" : ObjectId("584a7ec1309356d26bef1771"),
    "Name" : "Dilip Kumar Singh",
    "Salary" : 90000.0,
    "Project" : "Codeafri Mongodb, Mongodb atlas",
    "DOJ" : ISODate("2016-12-01T20:19:55.782Z")
}


Suppose I want to remove those documents which “Name” is “Vipul”. See the following query.


db.EMP.remove({'Name':'Vipul'})


Again execute the db.EMP.find() command to get document. And the output will be.


>db.EMP.find()

OutPut

/* 1 */
{
    "_id" : ObjectId("584a7ec1309356d26bef1773"),
    "Name" : "Ashish",
    "Salary" : 100000.0,
    "Project" : "Codeafri Project architect",
    "DOJ" : ISODate("2013-10-01T20:19:55.782Z")
}

/* 2 */
{
    "_id" : ObjectId("584a7ec1309356d26bef1771"),
    "Name" : "Dilip Kumar Singh",
    "Salary" : 90000.0,
    "Project" : "Codeafri Mongodb, Mongodb atlas",
    "DOJ" : ISODate("2016-12-01T20:19:55.782Z")
}



You can see document is not appears which was contains “Name” is “Vipul”.


Remove only one Document

Previously I have described just one option, here we will use this option to delete only one document. See the following example.


>db.EMP.remove({"Name":"Vipul"},1)


This query will remove only one document which has “Name” : “Vipul”.


Remove All Document


To remove all documents from a collection use the following command.


>db.EMP.remove()


There are no any parameters passed in remove method if you are not passing parameter deletion criteria or just one it means you want to remove all document from EMP collection.