0
0
MongoDBquery~5 mins

Soft delete pattern in MongoDB

Choose your learning style9 modes available
Introduction

Soft delete lets you mark data as deleted without removing it. This helps keep data safe and recoverable.

When you want to keep a record of deleted items for audit or history.
When users might want to undo a delete action.
When you want to avoid accidental data loss.
When you need to keep related data intact without breaking references.
When you want to filter out deleted items but keep them in the database.
Syntax
MongoDB
db.collection.updateOne(
  { _id: ObjectId("id_here") },
  { $set: { deleted: true, deletedAt: new Date() } }
)

Use a boolean field like deleted to mark if an item is deleted.

Optionally add a deletedAt timestamp to know when it was deleted.

Examples
Marks a user as deleted by setting deleted to true and recording the time.
MongoDB
db.users.updateOne(
  { _id: ObjectId("507f1f77bcf86cd799439011") },
  { $set: { deleted: true, deletedAt: new Date() } }
)
Soft deletes all products in the "old" category.
MongoDB
db.products.updateMany(
  { category: "old" },
  { $set: { deleted: true, deletedAt: new Date() } }
)
Finds all orders that are not marked as deleted.
MongoDB
db.orders.find({ deleted: { $ne: true } })
Sample Program

This example soft deletes one product by setting deleted to true and adds a timestamp. Then it finds all products that are still active (not deleted).

MongoDB
use shopDB

// Soft delete a product by id
const productId = ObjectId("642f1f77bcf86cd799439012")
db.products.updateOne(
  { _id: productId },
  { $set: { deleted: true, deletedAt: new Date() } }
)

// Query products that are not deleted
db.products.find({ deleted: { $ne: true } })
OutputSuccess
Important Notes

Remember to always filter out documents where deleted is true when querying active data.

Soft delete keeps data safe but can increase database size over time.

You can add a background job to permanently delete old soft deleted data if needed.

Summary

Soft delete marks data as deleted without removing it.

Use a deleted boolean and optional deletedAt timestamp.

Always filter queries to exclude soft deleted data unless you want to see it.