Open In App

MongoDB – Delete Multiple Documents Using MongoDB Shell

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The db.collection.deleteMany() method is used to delete multiple documents from a collection in Mongo Shell. This method deletes multiple documents from the collection according to the filter.

The deleteMany() is a Mongo shell method, which can delete multiple documents. This method can be used in multi-document transactions. If you use this method in a capped collection, then it will throw an exception.

Syntax

db.collection.deleteMany(
    <filter>,
   {
      writeConcern: <document>,
     collation: <document>
   }
)

Parameters

filter: First parameter of this method. It specifies the selection criteria for the deletion using query operators. The type of this parameter is a document. If it contains an empty document, i.e., {}, then this method will delete all the documents from the collection. 

Optional Parameters:

  • writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
  • collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.

Return: 

This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and deletedCount which represents the total number of deleted documents.

Delete Multiple Documents Using MongoDB Shell Examples

Let’s look at some examples of how to delete multiple documents using MongoDB Shell.

In the following examples, we are working with:

Database: GeeksforGeeks
Collection: contributor
Document: four documents that contain the details of the contributors in the form of field-value pairs.

sample database and collection

Delete Documents that Match a Filter Example

In this example, we are deleting multiple documents from the contributor collection that match the filter, i.e., language: “C#”.

deleting multiple documents example

Deleting All Documents Example

In this example, we are deleting all the documents from the contributor collection by passing empty documents in the db.collection.deleteMany() method.

db.contributor.deleteMany({})

delete all documents example output

Conclusion

In this article, we have explained how to delete multiple documents using Mongo Shell. To delete multiple documents from a collection, we can use the db.collection.deleteMany() method.

We have also seen two different use cases of db.collection.deleteMany() method. It can be used to delete documents that match the filter or delete all the documents from the collection.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads