Delete Documents

Delete Documents in MongoDB

Deleting data is an essential CRUD operation. MongoDB makes removing records simple and safe. You must always be careful when deleting data.

Deleting a Single Document

Use the deleteOne() method for precision. It removes the very first document that matches your filter. It is typically used with a unique _id.

Deleting Multiple Documents

Use deleteMany() for bulk removals. It deletes every document matching the criteria. Always double-check your filter before running this!

Deleting All Documents

You can empty a collection entirely. Run deleteMany({}) with an empty filter object. This keeps the collection intact but removes all rows.

Dropping vs Deleting

deleteMany({}) scans and removes documents. drop() deletes the entire collection instantly. drop() is much faster for clearing massive datasets.

Delete Examples:

// Delete one user by their unique ID
db.users.deleteOne({ _id: ObjectId("5f8a...") });

// Delete all users who are inactive db.users.deleteMany({ status: "inactive" });

// Delete absolutely everything in the collection db.users.deleteMany({});

Acknowledgment

Delete operations return a status object. It tells you how many records were successfully deleted. Check deletedCount to verify the operation.

Find and Delete

Sometimes you need the data one last time. Use findOneAndDelete() to retrieve it and remove it. It pops the document out of the database like a queue.

Soft Deletes

Many apps never actually delete data permanently. They use a "soft delete" strategy instead. This means updating a deletedAt field using $set.

Summary

Use deleteOne() for exact targeting. Use deleteMany() to clean up multiple records. Consider soft deletes for critical business applications.

Exercise

Which method is the absolute fastest way to remove all documents and the collection itself?