MongoDB Delete Documents – MongoDB CRUD Operations Part 3

In this chapter, we will talk about MongoDB delete documents – how to delete documents in the collection. There are many ways in MongoDB from which we can delete documents in the collection:

  • collection.remove()
  • collection.deleteOne() – New in version 3.2.
  • collection.deleteMany() – New in version 3.2.
  • collection.findOneAndDelete()

Let’s read about them in brief.

MongoDB Delete Documents


There are many methods to delete documents in MongoDB as mentioned above. Let’s go through these methods to understand it better.

  • db.collection.remove()

This method deletes a single document or all documents from the collection that match a specified filter. db.collection.remove() method works on two parameters.

  • Deletion criteria: Condition on which document has to be deleted.
  • JustOne: To remove only one document when set to true or 1.

Syntax:

E.g.: To remove all documents that match a condition:

This command will delete all the documents from the ‘TutorialsJar’ collection where ‘tutorial’ field is equal to ‘mongodb’.

E.g.: To remove a single document that matches a condition:

If you want to remove a single document that matches a given condition, then use the following syntax.

MongoDB Delete Documents

E.g.: To delete all the documents from the collection (i.e. without any condition)

2) db.collection.deleteOne()

This method deletes at most a single document that matches a specified filter even though multiple documents may match the specified filter. This is a new MongoDB delete documents method introduces in v3.2.

Syntax:

This is similar to db.collection.remove() method with the <justOne> parameter set to true or 1.

3) db.collection.deleteMany()

This method deletes all documents that match a specified filter. This is also a new MongoDB delete documents method introduces in v3.2.

This command will delete all the documents from the ‘TutorialsJar’ collection where ‘tutorial’ field is equal to ‘mongodb’.

4) db.collection.findOneAndDelete()

This method deletes a single document based on the filter and sort criteria, returning the deleted document.

Definition:

db.collection.findOneAndDelete(filter, options)

Syntax:

That’s it in this MongoDB delete documents – MongoDB CRUD Operations Part 3. If you have any queries, please comment in the comment section below. Also, do share your feedback 🙂

Mohit Arora
Follow me

Mohit Arora

Hi, I am Mohit Arora , a passionate blogger and addicted reader. Currently working as a Senior Systems Engineer in INFOSYS Ltd.
You can check my other blog - CatchUpdates.com

You can connect with me on Instagram Or Quora And Linkedin as well.
Mohit Arora
Follow me