MongoDB – Delete Multiple Documents Using MongoShell

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({})

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.