VOOZH about

URL: https://www.geeksforgeeks.org/node-js/mongoose-document-model-deletemany-api/

⇱ Mongoose Document Model.deleteMany() API - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Mongoose Document Model.deleteMany() API

Last Updated : 26 Sep, 2022

The Model.deleteMany() method of the Mongoose API is used to delete more than one document in the collection at a time in one go. We can provide an object which contains a condition to the deleteMany() and can be executed on the model object. It will delete all the documents from the collection that will match the given condition.

Syntax:

Model.deleteMany()

Parameters: The Model.deleteMany() method accepts three parameters:

  • condition: It is an object with a condition to filter the documents you are going to delete.
  • options: It is an object with various properties.
  • callback: It is a callback function that will run once execution is completed.

Return Value: The Model.deleteMany() function returns a promise. The result contains an object with the property name deletedCount indicating the number of documents deleted.

Setting up Node.js application:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this:

👁 Image
 

Database Structure: The database structure will look like this, the following documents are present in the collection.

👁 Image
 

Example 1: In this example, We have established a database connection using mongoose and defined model over studentSchema, having three columns or fields "name", "rollNumber", and "school". In the end, we are using deleteMany() method on the Student model which will delete all the documents from the collection that matches the condition. In this example, we are deleting a document that has "ABC" as a value to the "school" field.

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

{ acknowledged: true, deletedCount: 4 }

Example 2: In this example, We have established a database connection using mongoose and defined model over userSchema, having two columns or fields "name", and "age". In the end, we are using deleteMany() method on the User model which will delete all the documents from the collection that matches the condition. In this example, we are deleting a document that has "30" as value to "age" field.

👁 Image
 

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

{ acknowledged: true, deletedCount: 2 }

Reference: https://mongoosejs.com/docs/api/model.html#model_Model-deleteMany

Comment

Explore