11.4. Deleting Documents in MongoDB: Deleting Single and Multiple Documents
MongoDB, as a document-oriented database management system, offers various operations to manipulate stored data, including deleting documents. This chapter will cover how to delete single and multiple documents in MongoDB.
Exclusion of Single Documents
Deleting a single document is performed using the deleteOne()
method. This method removes the first document that matches the specified condition. The basic syntax for deleting a single document is as follows:
db.collection.deleteOne(query)
Where db
is the name of the database, collection
is the name of the collection and query
is the condition that the document must meet to be deleted.
For example, to delete a single document from the "students" collection where the "name" field equals "John", you would use the following command:
db.students.deleteOne({ "name" : "John" })
This command will return an object that contains information about the operation, including the number of documents deleted.
Multiple Document Deletion
To delete multiple documents that match a specific condition, you would use the deleteMany()
method. The basic syntax for deleting multiple documents is as follows:
db.collection.deleteMany(query)
For example, to delete all documents from the "students" collection where the "age" field is less than 20, you would use the following command:
db.students.deleteMany({ "age" : { $lt : 20 } })
This command will also return an object that contains information about the operation, including the number of documents deleted.
Delete All Documents
In some cases, you may want to delete all documents in a collection. This can be done using the deleteMany()
method without specifying a condition. The syntax for this is as follows:
db.collection.deleteMany({})
For example, to delete all documents from the "students" collection, you would use the following command:
db.students.deleteMany({})
This command will also return an object that contains information about the operation, including the number of documents deleted.
Important Considerations
It is important to note that deleting documents in MongoDB is an irreversible operation. Once a document is deleted, it cannot be recovered. Therefore, it is advisable to back up your data regularly and use deletion carefully.
Additionally, deleting documents can affect the performance of your database, especially if you are deleting a large number of documents at once. Therefore, it is advisable to monitor your database performance and plan delete operations during periods of low activity.
In summary, MongoDB offers several ways to delete documents, whether it is a single document, multiple documents, or all documents in a collection. However, since deletion is an irreversible operation, it is important to use it carefully and back up your data regularly.