MongoDB Delete Document

Delete document is used to delete an exiting document from a collection. The remove() method is used for removing the documents from a collection in MongoDB.

Delete Document Syntax :

The syntax of the Delete Document is −

 
\\Delete Document in MongoDB 
db.collection_name.remove(delete_criteria)


Delete Document Example :

The Example of the Delete Document is −

Now we are deleting a document from the collection named mydbs.

\\The documents in mydbs collection are:
> db.mydbs.find().pretty()
{
"_id" : ObjectId("59bcecc7668dcce02aaa6fed"),
"StudentId" : 110,
"StudentName" : "smith",
"age" : 35
}
{
"_id" : ObjectId("59bcecc7668dcce02aaa6fef"),
"StudentId" : 143,
"StudentName" : "Randy",
"age" : 47
}
---------------------
---------------------
\\Remove a student from this collection who has a student ID equal to 143.
db.mydbs.remove({"StudentId": 143})
\\Output
WriteResult({ "nRemoved" : 1 })


Verification :

To verify whether the document is actually deleted. Type the following command:−

\\Command for verification
db.mydbs.find().pretty()
---------------------
---------------------
\\You would see this output:
> db.mydbs.find().pretty()
{
"_id" : ObjectId("59bcecc7668dcce02aaa6fed"),
"StudentId" : 110,
"StudentName" : "smith",
"age" : 35
}






Visit :


Discussion



* You must be logged in to add comment.