Site icon DataFlair

MongoDB Delete Document with Methods and Examples

MongoDB Delete Document

MongoDB Delete Document

FREE Online Courses: Transform Your Career – Enroll for Free!

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.

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.

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.

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

Let’s confirm it by running a query.

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 – db.collection.deleteMany() Method

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

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.

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

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.

Exit mobile version