Open In App

MongoDB – Delete Multiple Documents Using MongoShell

Improve
Improve
Like Article
Like
Save
Share
Report

In MongoDB, you are allowed to delete the existing documents from the collection using db.collection.deleteMany() method. This method deletes multiple documents from the collection according to the filter.

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

Syntax:

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

Parameters:

fileter: First parameter of this method. It specifies the selection criteria for the delete using query operators. The type of this parameter is document. If it contains 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 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 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 that represents the total number of deleted documents.

Examples:

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.

Deleting documents that matches the filter:

In this example, we are deleting multiple documents from the contributor collection that matches the filter, i.e., language: “C#”. Or in other words, we are removing those contributors who are working with C# language from the database.

Deleting all documents:

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

db.contributor.deleteMany({})


Last Updated : 27 Feb, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads