0
0
MongoDBquery~5 mins

Delete with filter conditions in MongoDB

Choose your learning style9 modes available
Introduction

Deleting with filter conditions helps you remove only the data you want, not everything. It keeps your database clean and organized.

Remove all users who have not logged in for over a year.
Delete products that are out of stock.
Clear old logs older than 30 days.
Remove temporary data after processing is done.
Syntax
MongoDB
db.collection.deleteMany({ filter })
db.collection.deleteOne({ filter })

deleteMany removes all documents matching the filter.

deleteOne removes only the first document matching the filter.

Examples
Deletes all users younger than 18 years old.
MongoDB
db.users.deleteMany({ age: { $lt: 18 } })
Deletes the first order found with status 'cancelled'.
MongoDB
db.orders.deleteOne({ status: 'cancelled' })
Deletes all logs before January 1, 2023.
MongoDB
db.logs.deleteMany({ date: { $lt: new Date('2023-01-01T00:00:00Z') } })
Sample Program

This example deletes all products with zero stock from the 'products' collection in the 'shopDB' database. It then prints how many products were deleted.

MongoDB
use shopDB

// Delete all products that are out of stock
const result = db.products.deleteMany({ stock: 0 })

// Show how many were deleted
print('Deleted count:', result.deletedCount)
OutputSuccess
Important Notes

Always double-check your filter before deleting to avoid removing wrong data.

Use deleteOne when you want to remove only a single matching document.

Deleting without a filter removes all documents, so be careful!

Summary

Use filter conditions to delete only specific documents.

deleteMany removes all matching documents; deleteOne removes just one.

Check your filters carefully to keep your data safe.