Sling Academy
Home/MongoDB/MongoDB deleteMany() method: A developer’s guide (with examples)

MongoDB deleteMany() method: A developer’s guide (with examples)

Last updated: February 03, 2024

Introduction

MongoDB, the popular NoSQL database favored for its scalability and performance, offers developers a range of methods to handle data manipulation tasks such as inserting, querying updating, and deleting documents. One such method is deleteMany(), which is designed to delete multiple documents from a collection that match a given query criteria. In this tutorial, you will learn how to effectively use the deleteMany() method, with practical examples ranging from basic to advanced use cases.

Before starting with the deleteMany() method, ensure you have MongoDB set up on your system and have basic understanding of MongoDB’s operations. We’ll assume you’re using MongoDB’s native driver for Node.js, but the concepts translate across other drivers as well.

Basics of deleteMany()

The deleteMany() method is a part of MongoDB’s CRUD (Create, Read, Update, and Delete) operations. As the name suggests, it is used to delete more than one document that satisfies the specified criteria. The general syntax is as follows:

db.collection.deleteMany(filter, options)

The filter parameter specifies the deletion criteria, while options is an optional parameter for additional command options. If you want to delete all documents from a collection, you can pass an empty filter object, like {}.

Example 1: Deleting Multiple Documents

Imagine you have a collection called ‘posts’ with various documents. Now, you want to delete all posts that have been tagged as ‘archived’. Here’s how you would use deleteMany():

// Connect to the MongoDB client
const MongoClient = require('mongodb').MongoClient;
const url = 'your_mongodb_url';

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  const dbo = db.db('mydatabase');

  const query = { tag: 'archived' };
  dbo.collection('posts').deleteMany(query, function(err, obj) {
    if (err) throw err;
    console.log(obj.result.n + ' documents deleted');
    db.close();
  });
});

In the output, you’ll get the number of documents that were deleted:

3 documents deleted

Example 2: Using Options Parameter

The options parameter allows you to specify various settings such as write concern. Suppose you’re working on a critical task that requires acknowledgment from the database that the write operation has been committed to the journal. To achieve this, you’d do:

// ...previous code

  const options = { writeConcern: { w: 'majority', j: true } };
  dbo.collection('posts').deleteMany(query, options, function(err, obj) {
    // ...rest of the callback
  });

// ...closing connection

Advanced Usage of deleteMany()

Example 3: Deleting with Complex Queries

Sometimes the criteria to delete documents can be complex, involving multiple fields and conditions. For instance, you might want to delete all ‘posts’ documents that are either tagged as ‘archived’ or have a view count less than 50:

// ...previous code

  const query = {
    $or: [{tag: 'archived'}, {views: { $lt: 50 }}]
  };

  dbo.collection('posts').deleteMany(query, function(err, obj) {
    // ...rest of the callback
  });

// ...closing connection

This will remove all documents that fulfill either of the conditions listed in the $or array.

Example 4: Incorporating deleteMany() into Transactions

In MongoDB, transactions allow you to execute multiple operations in an atomic manner. Here’s a way to use deleteMany() within a transaction:

// ...previous code

const session = db.startSession();
session.startTransaction();

try {
  const query = { status: 'pending' };
  const deletionResult = dbo.collection('orders').deleteMany(query, { session: session });
  console.log(deletionResult.result.n + ' pending orders deleted');

  // Commit the transaction
  await session.commitTransaction();
} catch (e) {
  // Abort the transaction
  await session.abortTransaction();
} finally {
  // End the session
  session.endSession();
  db.close();
}

Handling Errors and Best Practices

It’s essential to handle potential errors when performing delete operations. A best practice is to wrap your deleteMany() calls in try-catch blocks or handle errors in callbacks, depending on whether you’re using promises or callbacks. Additionally, considering the potentially destructive nature of delete operations, always ensure that your deletion criteria are accurate to prevent unintended data loss.

Scaling Considerations

When working with large-scale data, deleting many documents at once can impact the performance. In such cases, consider using bulk write operations or plan your deletions during low-traffic times to minimize impact on database performance.

Conclusion

In this tutorial, you’ve learned how to use MongoDB’s deleteMany() method to remove documents from a collection. Through the examples provided, you’ve seen the method can handle simple to complex and even transaction-wrapped delete operations. Remember to use the delete pattern judiciously and to handle errors properly to maintain the integrity and performance of your applications.

Next Article: MongoDB remove() method – Explained with examples

Previous Article: MongoDB deleteOne() method: A practical guide (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)