MongoDB Delete Document with Methods and Examples

We offer you a brighter future with FREE online courses - 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.

MongoDB Delete Document

Delete Document in MongoDB – db.collection.deleteOne() Method

This collection has two documents with two fields that have different values. Now, let’s use this method for the criteria set.

MongoDB Delete Document

Delete Document in MongoDB – db.collection.deleteOne() Method

Let’s confirm it by running a query.

MongoDB Delete Document

Delete Document in MongoDB – db.collection.deleteOne() Method

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.

MongoDB Delete Document

MongoDB Delete Document – db.collection.deleteMany() Method

Now let’s delete more than one document that matches the criteria.

MongoDB Delete Document

MongoDB Delete Document – db.collection.deleteMany() Method

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.

MongoDB Delete Document

Delete Document in MongoDB – db.collection.remove() 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().

Delete Document in MongoDB - db.collection.remove() Method

Delete Document in MongoDB – db.collection.remove() Method

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 this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *