MongoDB - Delete Document
In this chapter, we will learn how to delete a document using MongoDB.
The remove() Methodβ
MongoDB's remove()
method is used to remove a document from the collection. The remove()
method accepts two parameters: one is the deletion criteria and the second is the justOne
flag.
- deletion criteria β (Optional) The criteria according to which documents will be removed.
- justOne β (Optional) If set to
true
or1
, then only one document will be removed.
Syntaxβ
The basic syntax of the remove()
method is as follows:
> db.COLLECTION_NAME.remove(DELETION_CRITERIA)
Exampleβ
Consider the mycol
collection has the following data:
{ "_id" : ObjectId("507f191e810c19729de860e1"), "title": "MongoDB Overview" },
{ "_id" : ObjectId("507f191e810c19729de860e2"), "title": "NoSQL Overview" },
{ "_id" : ObjectId("507f191e810c19729de860e3"), "title": "Tutorials Point Overview" }
Following example will remove all the documents whose title is 'MongoDB Overview'.
> db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({ "nRemoved" : 1 })
> db.mycol.find()
{ "_id" : ObjectId("507f191e810c19729de860e2"), "title": "NoSQL Overview" }
{ "_id" : ObjectId("507f191e810c19729de860e3"), "title": "Tutorials Point Overview" }
Remove Only Oneβ
If there are multiple records and you want to delete only the first record, then set the justOne
parameter in the remove()
method.
> db.COLLECTION_NAME.remove(DELETION_CRITERIA, 1)
Remove All Documentsβ
If you don't specify deletion criteria, then MongoDB will delete all documents from the collection. This is equivalent to SQL's TRUNCATE
command.
> db.mycol.remove({})
WriteResult({ "nRemoved" : 2 })
> db.mycol.find()
Diagramsβ
Remove Document Flowβ
Notesβ
- Always double-check your deletion criteria to avoid accidental removal of unintended documents.
- Use
justOne
flag to limit deletion to a single document if needed. - Omitting the deletion criteria will result in removing all documents from the collection.
Table of Commandsβ
Command | Description |
---|---|
db.COLLECTION_NAME.remove(DELETION_CRITERIA) | Removes documents matching the criteria. |
db.COLLECTION_NAME.remove(DELETION_CRITERIA, 1) | Removes only the first document matching the criteria. |
db.COLLECTION_NAME.remove({}) | Removes all documents from the collection. |