MongoDB Delete Many Documents



MongoDB Delete Many Documents

In MongoDB, the deleteMany operation is used to remove multiple documents from a collection that match a specified filter. This method is essential for managing and maintaining data integrity within MongoDB collections.


Syntax

db.collection.deleteMany(filter, options)

The deleteMany method takes a filter to specify which documents to remove and an optional options parameter to customize the deletion.


Example MongoDB Delete Many Documents

Let's look at an example of how to use the deleteMany method in the programGuru collection in MongoDB:

1. Delete Multiple Documents

db.programGuru.deleteMany({ age: { $gt: 30 } })

This command deletes all documents where the age is greater than 30 in the programGuru collection.


Full Example

Let's go through a complete example that includes switching to a database, creating a collection, inserting documents, and deleting multiple documents.

Step 1: Switch to a Database

This step involves switching to a database named myDatabase.

use myDatabase

In this example, we switch to the myDatabase database.

MongoDB Delete Many Documents

Step 2: Create a Collection

This step involves creating a new collection named programGuru in the myDatabase database.

db.createCollection("programGuru")

Here, we create a collection named programGuru.

MongoDB Delete Many Documents

Step 3: Insert Documents into the Collection

This step involves inserting documents into the programGuru collection.

db.programGuru.insertMany([
    { name: "John Doe", age: 30, email: "john.doe@example.com" },
    { name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
    { name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])

We insert multiple documents into the programGuru collection.

MongoDB Delete Many Documents

Step 4: Delete Multiple Documents from the Collection

This step involves using the deleteMany method to remove documents from the programGuru collection.

db.programGuru.deleteMany({ age: { $gt: 30 } })

We delete all documents where the age is greater than 30.

MongoDB Delete Many Documents

Conclusion

The MongoDB deleteMany operation is crucial for managing data within collections. Understanding how to use this method allows you to efficiently remove specific documents, ensuring data integrity and proper management in MongoDB collections.