Learn

We now know how to delete a single document from a collection, but what if we want to delete multiple documents that match certain criteria? We can accomplish this with the .deleteMany() method.

The .deleteMany() method removes all documents from a collection that match a given filter. This method uses the following syntax:

db.<collection>.deleteMany(<filter>, <options>);

Note in the syntax above that the .deleteMany() method takes two arguments:

  • filter: A document that provides selection criteria for the documents to delete.
  • options: A document where we can include optional fields to provide more specifications to our operation, such as a writeConcern.

Warning: If no filter is provided to the .deleteMany() method, all documents from the collection will be deleted.

Let’s revisit the original monsters collection from the previous exercise. Consider a new monster with the name of "Pat" was recently added:

{ _id: ObjectId("629a1e8c2bf029cc101c92d4"), name: "Luca", age: 100, type: "Hydra" }, { _id: ObjectId("629a2245b8bd9cad32a210fa"), name: "Lola", age: 95, type: "Hydra" }, { _id: ObjectId("629a225119915a53df5b428c"), name: "Igor", age: 85, type: "Hydra" }, { _id: ObjectId("629a226c8982a4dd04e093ff"), name: "Pat", age: 85, type: "Dragon" }

We now want to get rid of all the monsters with a type field with the value of "Hydra". We could run the .deleteOne() method and pass in the filter {type: "Hydra"}, but we would need to execute the method multiple times. This could quickly get very tedious. Instead, let’s use .deleteMany():

db.monsters.deleteMany({ type: "Hydra" });

Once executed, the operation will successfully delete all documents where the type field has the value of "Hydra". MongoDB will confirm if the operation was successful and let us know how many documents were deleted with the following output:

{ acknowledged: true, deletedCount: 3 }

This would leave us with a single remaining document:

{ _id: ObjectId("629a226c8982a4dd04e093ff"), name: "Pat", age: 85, type: "Dragon" }

Now that we’ve gotten familiar with the .deleteMany() method, let’s get some practice with it.

Instructions

1.

Connect to the restaurants database. Then, using the listingsAndReviews collection, query the restaurants collection for restaurants in the borough of "Rhode Island".

2.

Uh oh! This must be a mistake. Rhode Island is a state, not a New York City borough. Delete all documents with the field borough that have the value "Rhode Island".

3.

Search the listingsAndReviews collection again to confirm that no documents are in the borough of "Rhode Island".

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?