Understanding Mongoose deleteMany() function (with examples)

Updated: December 30, 2023 By: Guest Contributor Post a comment

Introduction

Mongoose is a widely used Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straight-forward, schema-based solution to model your application data. The deleteMany() function is a part of Mongoose’s arsenal of methods that allow for bulk deletion of documents matching given criteria.

The deleteMany() function was introduced to Mongoose to improve developer experience by enabling bulk deletion operations directly, which resemble MongoDB’s raw CRUD operations capabilities. Precise details about when it was added can be obtained from the Mongoose and MongoDB release notes.

The primary purpose of deleteMany() is to delete multiple documents from a collection that match a given filter. It’s a more efficient way to remove documents in bulk, as opposed to calling deleteOne() multiple times.

Syntax and Parameters

Model.deleteMany(query, [options], [callback])

Arguments:

  • query: The filter used to select documents for removal.
  • options: (optional) Additional options passed to the MongoDB driver method, such as write concern.
  • callback: (optional) A function that gets called after deletion. If omitted, a Promise is returned.

The function returns a Promise which resolves to an object containing the outcome of the operation.

Code Examples

Basic deletion

This example demonstrates how to delete all documents that match a specific condition.

Introduction: Let’s say you have a collection of “users” and you want to delete all users who are marked as inactive.

import mongoose from 'mongoose';
const User = mongoose.model('User', new mongoose.Schema({ inactive: Boolean }));
async function deleteInactiveUsers() {
  const result = await User.deleteMany({ inactive: true });
  console.log(result);
}
deleteInactiveUsers();

Deletion with options

In this example, we add an option to our deletion to specify a write concern.

async function deleteInactiveUsersWithWriteConcern() {
  const result = await User.deleteMany({ inactive: true }, { writeConcern: { w: 'majority' } });
  console.log(result);
}
deleteInactiveUsersWithWriteConcern();

Using Callback

For those who prefer callback style programming, here’s how to use deleteMany() with a callback.

User.deleteMany({ inactive: true }, (err, result) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(result);
});

Conclusion

The deleteMany() function is a powerful feature in Mongoose that allows for efficient bulk deletion of documents. By properly using this function, you can manage your MongoDB collections more effectively, ensuring that unnecessary data doesn’t accumulate, and your database operations remain fast. As with all operations that alter your database, use deleteMany() cautiously and always be aware of its implications.