Sling Academy
Home/Node.js/Understanding Mongoose deleteMany() function (with examples)

Understanding Mongoose deleteMany() function (with examples)

Last updated: December 30, 2023

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.

Next Article: Mongoose: Sorting Documents by Multiple Fields

Previous Article: Using the Mongoose Model.find() function (with examples)

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates