MongoDB deleteMany()

In MongoDB the db.collection.deleteMany() method removes all documents that match the filter from a collection. In other words, it deletes them.

The collection part is the name of the collection with which to remove the documents from.

Delete All Documents

In this example, we delete all documents from a collection called employees:

db.employees.deleteMany({})

Result:

{ "acknowledged" : true, "deletedCount" : 5 }

The result shows us that five documents were removed.

Remove Selected Documents

In this example, we remove only some documents.

First, let’s populate our employees collection again:

db.employees.insertMany([
    { _id: 1, name: "Sandy", salary: 55000 },
    { _id: 2, name: "Sarah", salary: 128000 },
    { _id: 3, name: "Fritz", salary: 25000 },
    { _id: 4, name: "Chris", salary: 45000 },
    { _id: 5, name: "Beck", salary: 82000 }
    ])

Now, let’s delete all employees that earn more than 80,000 per year.

db.employees.deleteMany({ "salary": { $gt: 80000 } })

Result:

{ "acknowledged" : true, "deletedCount" : 2 }

This time only two documents were deleted.

Let’s take a look at the collection.

db.employees.find()

Result:

{ "_id" : 1, "name" : "Sandy", "salary" : 55000 }
{ "_id" : 3, "name" : "Fritz", "salary" : 25000 }
{ "_id" : 4, "name" : "Chris", "salary" : 45000 }

As expected, the two top salary earners have left the company.

Delete One Document

If you need to delete a specific document, you can specify the document’s _id value (or some other value unique to that document) to remove that specific document.

So if we wanted to delete Fritz from the above collection, we could specify his _id value of 3. Like this:

db.employees.deleteMany({ "_id": 3 })

Result:

{ "acknowledged" : true, "deletedCount" : 1 }

Let’s check the collection again:

db.employees.find()

Result:

{ "_id" : 1, "name" : "Sandy", "salary" : 55000 }
{ "_id" : 4, "name" : "Chris", "salary" : 45000 }

As expected, Fritz has now disappeared.

More Information

The db.collection.deleteMany() method also accepts optional parameters such as collation, hint, and writeConcern.

See the MongoDB documentation for more information.