Mongoose deleteMany() Function
The deleteMany() function is employed to remove all documents meeting specified conditions from a collection. Unlike the remove() function, deleteMany() deletes all matching documents without considering the single option.
Syntax:
Model.deleteMany()
Parameters: The Model.deleteMany() method accepts three parameters:
- docs: It is an array of objects which will be inserted into the collection.
- options: It is an object with various properties.
- callback: It is a callback function that will run once execution is completed.
Returns: The Model.deleteMany() function returns a promise. The result contains an array of objects having details of documents inserted in the database.
Steps to Installation of Mongoose Module:
Step 1: You can visit the link Install Mongoose module. You can install this package by using this command.
npm install mongoose
Step 2: After installing the mongoose module, you can check your mongoose version in the command prompt using the command.
npm version mongoose
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"mongoose": "^7.6.5",
}
Example: Below the code example for the deleteMany() method:
Javascript
const mongoose = require( 'mongoose' ); // Database connection mongoose.connect( 'mongodb://127.0.0.1:27017/w3wiki' , { useNewUrlParser: true , useCreateIndex: true , useUnifiedTopology: true }); // User model const User = mongoose.model( 'User' , { name: { type: String }, age: { type: Number } }); // Function call // Deleting all users whose age >= 15 User.deleteMany( { age: { $gte: 15 } }).then( function () { // Success console.log( "Data deleted" ); }). catch ( function (error) { // Failure console.log(error); }); |
Steps to run the program:
node index.js
Output:Below is the sample data in the database before the deleteMany() function is executed:Console Output:
After running above command, you can see the data is deleted from the database.
So this is how you can use mongoose deleteMany() function to delete multiple documents from the collection in MongoDB and Node JS.