Delete Documents - CRUD Operations
In MongoDB, deleting documents is part of the CRUD (Create, Read, Update, Delete) operations. In this page, we will discuss how to delete documents from a MongoDB database.
Syntax
The basic syntax for deleting a document in MongoDB is as follows:
db.collection.deleteOne(
<filter>,
<options>
)
The deleteOne()
method deletes a single document that matches the specified filter. You can use deleteMany()
method to delete multiple documents with a single operation.
Example
Consider the following inventory
collection with sample data:
{ "_id" : 1, "item" : "apple", "qty" : 5 }
{ "_id" : 2, "item" : "banana", "qty" : 10 }
{ "_id" : 3, "item" : "orange", "qty" : 2 }
{ "_id" : 4, "item" : "peach", "qty" : 8 }
To delete a single document that matches a specified filter, you can use the deleteOne()
method as shown below:
db.inventory.deleteOne(
{ "item": "banana" }
)
This will delete the document with "item"
value of "banana"
and return a DeleteResult
object.
Output
The DeleteResult
object contains information about the delete operation, including the number of documents deleted, and the acknowledged
status of the operation.
Explanation
Deleting a document from a MongoDB collection removes the document from the collection and the database. MongoDB provides various methods to delete documents from a collection, including deleteOne()
and deleteMany()
methods. You can use these methods to delete one or more documents that match a specified filter.
Use
Deleting documents in MongoDB can be useful for removing outdated or irrelevant data that is no longer needed by your application. This can help to free up disk space and improve overall performance.
Important Points
- You can use
deleteOne()
method to delete a single document that matches a specified filter. - The
deleteMany()
method can be used to delete multiple documents with a single operation. - Deleting documents deletes the document from the collection and the database.
Summary
In this page, we discussed how to delete documents from a MongoDB database using the deleteOne()
method. We covered the syntax, example, output, explanation, use, important points, and summary of the delete operation. By removing unnecessary data, you can improve the performance and efficiency of your application.