Last Updated: 14 August, 2023
In MongoDB, we can delete or remove one or more documents from the collection using the following methods:
Method Name | Description |
---|---|
db.collection.deleteOne() | Removes a single document from a collection. |
db.collection.deleteMany() | Removes multiple documents that match the filter from a collection. |
Both delete methods are added in the MongoDB 3.2 version.
We can specify the condition for delete operations, which means we delete some specific types of documents from the collection based on the requirement. These conditions work the same as read operations in MongoDB.
In MongoDB, All write operations are atomic at the level of a single document.
Let's see examples of deleting documents from a collection in MongoDB.
For example, suppose we have a collection named student which has the following documents as given below:
[ {sid: 1, name: 'Ramesh', class: 'Nursery', roll: 15, gender: 'M'}, {sid: 2, name: 'Gyatri', class: 'LKG', roll: 18, gender: 'F'}, {sid: 3, name: 'John', class: 'Nursery', roll: 26, gender: 'M'}, {sid: 4, name: 'Priya', class: 'UKG', roll: 10, gender: 'F'}, {sid: 5, name: 'Suraj', class: 'LKG', roll: 12, gender: 'M'} ]
To delete a single document from a collection in MongoDB, we use the deleteOne() method. See the examples below.
db.student.deleteOne({class: 'Nursery'});
Here, we are deleting a single document from the collection whose class field value is Nursery. If multiple documents are found, then it will delete the first matching document from the collection. After successful document deletion, we will get the below output:
Output
/ 1 / { "acknowledged" : true, "deletedCount" : 1 }
MongoDB also allows us to delete multiple documents from a collection using the deleteMany() method. See the examples below.
db.student.deleteMany({class: 'Nursery'});
Here, we are deleting multiple documents from the collection whose class field value is Nursery. After successful document deletion, we will get the below output:
Output
/ 1 / { "acknowledged" : true, "deletedCount" : 2 }
In MongoDB, we can delete all the documents from a collection, we can do so by passing an empty filter document {} to the db.collection.deleteMany() method. See the examples below.
db.student.deleteMany({});
Output
/ 1 / { "acknowledged" : true, "deletedCount" : 4 }
After deleting all documents from a collection, if we run the find() method, we will get an empty result. See the example below.
db.student.find();
Output
Script executed successfully, an empty result returned.
Reference: https://www.mongodb.com/docs/mongodb-shell/crud/delete/
That's all, guys. I hope this MongoDB article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com