As a full-stack developer, working with databases is an integral part of our day-to-day work. MongoDB has become one of the most popular document-oriented NoSQL databases used by developers. Its flexible and scalable data model makes it well-suited for modern applications.

One of the great aspects of MongoDB is the rich set of methods available to manipulate data. In this comprehensive guide, we‘ll explore one powerful method – deleteMany().

We‘ll cover the working, syntax, various usage scenarios and best practices around using this method efficiently.

How deleteMany() Works Internally

Let‘s first understand what happens internally when you call the deleteMany() method.

  • The method looks up documents in the collection that match the filter criteria passed to it. This uses the same find/query mechanics internally.

  • It notes down identifiers of the matched documents.

  • Then it calls the delete operation using these identifiers to remove the matched documents from the collection.

  • The objects are marked for deletion and removed from indexes. The underlying storage for these documents is reclaimed lazily by the system later.

  • Finally stats about the operation including number of deleted docs is returned.

This is how deleteMany() is able to locate matching documents efficiently and delete them in one call. The filter criteria and options offer flexibility to fine tune this behaviour.

Syntax and Parameters

The basic syntax of deleteMany() method is:

db.collection.deleteMany(
   <filter>,
   <options>
)

It takes two parameters:

filter

This is the selection criteria to find and delete documents. It uses the standard MongoDB query filter syntax.

You can specify conditions on any field(s), use comparison operators like $gt, $in etc. or complex logical expressions.

If an empty filter {} is passed, all documents are deleted.

options

This is an optional document to specify options like:

{
  writeConcern: <document>,
  collation: <document> 
}
  • writeConcern allows specifying custom write concern. The default acknowledgement is sufficient for most cases.

  • collation specifies language-specific string comparison rules.

Next let‘s go over some usage examples.

Deleting All Documents in a Collection

Deleting all documents in a collection can be achieved by passing an empty filter document:

db.products.deleteMany({})

This removes all documents from products collection.

The method returns output containing deleted docs count:

{
  "acknowledged" : true,
  "deletedCount" : 10
}  

Advantages:

  • Simple, no need to specify any criteria
  • Fast deletion of entire collection

Use cases:

  • Refreshing test collections with sample data
  • Periodically cleansing temporary collections

Delete by Field Value

The power of deleteMany() lies in deleting specific documents based on field values or conditions.

Exact Match on a Field

For example, delete products with status "disabled":

db.products.deleteMany({ status: "disabled" })  

This evaluates the status field against "disabled" value and removes matching documents.

Match Field against a Value Set

You can also match against a set of values using the $in operator.

For example, delete products with status as either "disabled" or "expired":

db.products.deleteMany({status: {$in: ["disabled", "expired"]}})

The $in operator matches status against both values.

This field-based deletion allows surgically targeting documents to be removed from your collections.

Leverage Comparison Query Operators

MongoDB supports rich comparison operators that come in handy for sophisticated delete rules.

For example, delete products priced greater than 100 dollars:

db.products.deleteMany({price: {$gt: 100}})

The $gt (greater than) operator deletes all products where price exceeds 100.

Here are some commonly used comparison operators:

Operator Description Example
$eq Equal to value {price: {$eq: 100}}
$gt Greater than {price: {$gt: 100}}
$gte Greater than or equal {price: {$gte: 50}}
$in One of values in set {cat: {$in: ["tech", "auto"]}}
$lt Less than {price: {$lt: 500}}
$lte Less than equal {price: {$lte: 100}}
$ne Not equal to {status: {$ne: "active"}}
$nin None of set values {origin: {$nin: ["US"]}}

You can combine these operators with logical operators to create sophisticated filters, like:

// Delete products with price $gt 1000 or $lt 50 
db.products.deleteMany(
    {$or: [ 
          {price: {$gt: 1000}},
          {price: {$lt: 50}}
        ]
    }
)

Here $or combines two $gt / $lt comparisons to target productsoutside 50-1000 price range.

Such precise delete rules help automatically get rid of unwanted documents.

Take Advantage of Logical Operators

MongoDB offers powerful logical operators like OR, AND and NOT to combine expression in complex ways.

For example, delete products that have (An "Electronics" category AND price less than 20) OR (price more than 1000) :

db.products.deleteMany({
    $or: [   
       { 
         $and: [
            {category: "Electronics"},  
            {price: {$lt:20}} 
         ]
       },
       {price: {$gt: 1000}}
    ]
})

Here $and finds affordable Electronics, while $or also selects very expensive products. Logical operators enable such sophisticated business logic directly in the database query!

Some commonly used logical operators are:

Logical Operator Description
$and Joins query clauses with AND logic
$not Negates the given query expression
$nor Negates OR logic between query expressions
$or Joins query clauses with OR logic

These operators help model complex decision logic for targeting document deletion.

Match on Array Fields in Documents

MongoDB offers flexible ways to work with array data in documents. The deleteMany() method works nicely to remove documents based on array content.

For example, delete products having the category "Books" inside an "categories" array:

db.products.deleteMany({categories: "Books"})

This will match products where "Books" exists in the categories array.

Useful ways to query array data are:

// Match documents where array field size is 3
db.products.deleteMany({sizes: {$size: 3}})

// Match using $all when array contains set of values   
db.products.deleteMany({regions: {$all: ["US", "UK"]}}) 

// Use $elemMatch to query array elements  
db.products.deleteMany({
    ratings: {
       $elemMatch: { 
          score: {$gte: 4}, 
          agency: "Consumer Trusted" 
        }  
    }
}) 

This flexibility helps manage documents using their array data effectively.

Target Embedded Documents with Dot Notation

In MongoDB, data for an entity can be organized across nested embedded documents using one-to-one, one-to-many or one-to-many relationships.

The deleteMany() method allows easily targeting embedded documents in parent documents by specifying dot notation.

For example, delete orders for customer "john123":

db.orders.deleteMany({"customer.username": "john123"}) 

Here customer.username focuses on the embedded customer document‘s username field , avoiding need to repeat full customer object match logic.

This is a compact yet powerful way to work with related or nested data in documents.

Optimizing deleteMany Performance

While deleteMany() provides rich functionality, certain best practices can help optimize its performance for large collections:

Create Index on Filter Fields

An index speeds up finding documents to remove. Create indexes on fields used extensively in deletes.

Do Deletes in Batches

Deleting thousands of documents in one shot can lock the database. Batch up deletes:

const batchSize = 1000;

db.orders.deleteMany({status: "inactive"}) // inactive orders 
db.orders.deleteMany({date: {$lt: twoYearsAgo}}) // old orders

Schedule off-peak Time

If deleting large number of docs, schedule it during off-peak hours to avoid interfering with regular database traffic.

Prefer deleteMany() over delete()

deleteMany() sends all deletes in one OP, reducing overhead compared to multiple delete() calls.

Such optimizations help scale delete heavy workloads for large MongoDB installations.

Alternative Document Update

In some cases you may alternatively want to update documents rather than delete them. This retains document IDs and some metadata.

For example flag inactive products instead of deleting:

db.products.updateMany(
    {lastOrdered: {$lt: twoYearsAgo}}, 
    {$set: {status:"inactive"}}
)

This sets status to "inactive" on matching old products.

So consider if updating documents status/flags/categories meets your app needs instead of actual deletes.

Comparison with deleteOne()

The related deleteOne() method also removes documents matching a filter. Key differences:

  • deleteOne() removes at most one document, even if filter matches multiple.
  • deleteMany() removes all matching documents in one call.

So deleteOne() is useful for deleting one arbitrary document matching a filter. On the other hand, deleteMany() enables removing multiple or all matches in an efficient one-shot manner.

Summary

As we‘ve explored, MongoDB‘s deleteMany() provides extensive yet easy ways to remove documents, making it a very handy part of the MongoDB skillset.

Some key takeways are:

  • Flexible criteria using field values, comparison and logical filters
  • Powerful operators like $or, $gt to target documents
  • Can delete all documents easily or batches
  • Embedded document support using dot notation
  • Manage array data seamlessly

I hope you find this guide useful in clearly understanding deleteMany() usage, operators and best practices. Do leave me any feedback or queries you may have.

Happy deleting your MongoDB documents!

Similar Posts