0
0
MongoDBquery~5 mins

deleteMany method in MongoDB

Choose your learning style9 modes available
Introduction

The deleteMany method helps you remove multiple records from a collection that match a condition. It keeps your data clean and organized.

You want to delete all users who have not logged in for over a year.
You need to remove all products that are out of stock.
You want to clear all temporary data older than a certain date.
You want to delete all comments flagged as spam.
You want to remove all entries with a specific status.
Syntax
MongoDB
db.collection.deleteMany(filter, options)

filter specifies which documents to delete.

options is optional and can include settings like write concern.

Examples
Deletes all users younger than 18 years old.
MongoDB
db.users.deleteMany({ age: { $lt: 18 } })
Deletes all orders with status 'cancelled'.
MongoDB
db.orders.deleteMany({ status: "cancelled" })
Deletes all logs before January 1, 2023.
MongoDB
db.logs.deleteMany({ timestamp: { $lt: new Date('2023-01-01') } })
Sample Program

This command deletes all documents in the inventory collection where the category is 'electronics'.

MongoDB
db.inventory.deleteMany({ category: "electronics" })
OutputSuccess
Important Notes

If no documents match the filter, deleteMany deletes nothing but still returns success.

Be careful with the filter to avoid deleting more data than intended.

deleteMany returns an object showing how many documents were deleted.

Summary

deleteMany removes multiple documents matching a filter.

It is useful for cleaning up data in bulk.

Always double-check your filter to avoid accidental data loss.