MongoDB Delete Document with Methods and Examples
Job-ready Online Courses: Click, Learn, Succeed, Start Now!
In our Previous Tutorial, we have studied How MongoDB Update Document – Insert & Query. Here, in this MongoDB tutorial, we are going to study How MongoDB Delete Document. In addition, we will discuss methods which are used for delete document in MongoDB.
So, let’s start – MongoDB Delete Document.
MongoDB Delete Document
MongoDB provides the option to delete the documents from the collection. You can delete one, many or all of the documents. There are three methods in MongoDB to delete documents as discussed below.
- db.collection.deleteOne() Method
- db.collection.deleteMany() Method
- db.collection.remove() Method
a. The db.collection.deleteOne() Method
This method deletes only one document from the collection, even if multiple documents match the criteria.
Let’s see an example of this method.
First, let’s query which shows multiple documents.
This collection has two documents with two fields that have different values. Now, let’s use this method for the criteria set.
Let’s confirm it by running a query.
b. The db.collection.deleteMany() Method
This method deletes all the documents that match the criteria. Let’s see the documents that we have in “dataflair” collection.
Now let’s delete more than one document that matches the criteria.
We have deleted two documents from the collection. A message displays as:
{“acknowledged”: true, “deletedCount”:2)
This shows that 2 documents have been deleted.
c. The db.collection.remove() Method
You can delete one or all the documents that match the specified criteria by using this method.
We have removed one document from the collection using remove() method. We can also delete all the documents just by leaving the filter in remove().
So, this was all about MongoDB Delete Document Tutorial. Hope you like our explanation.
Conclusion
Hence, we study MongoDB Delete Document. At last, we discuss different Methods of delete documents in MongoDB in detail. Furthermore, if you have any query, feel free to ask in the comment section.
Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google