Deleting Documents Safely With deleteOne and deleteMany
Learners will remove single or multiple documents and discuss strategies for preventing accidental mass deletions.
Permanent Deletion in MongoDB
MongoDB provides two methods for removing documents:
- deleteOne(filter) — removes the first document that matches the filter and returns
{ acknowledged, deletedCount } - deleteMany(filter) — removes all documents matching the filter and returns the total
deletedCount
Unlike SQL's DELETE, MongoDB deletes are permanent and immediate—there is no transaction-based undo once the operation is acknowledged (unless you are within a multi-document transaction that has not yet committed). Always use deletes with careful, targeted filters.
// deleteOne: removes first matching document
const res1 = await db.collection('sessions').deleteOne(
{ token: expiredToken }
);
console.log(res1.deletedCount); // 0 or 1
// deleteMany: removes all matching documents
const res2 = await db.collection('sessions').deleteMany(
{ expiresAt: { $lt: new Date() } }
);
console.log(res2.deletedCount); // 0 or moreThe Danger of deleteMany({})
An empty filter {} in deleteMany deletes every document in the collection. This is equivalent to TRUNCATE TABLE in SQL and is one of the most dangerous accidental operations in MongoDB. Unlike SQL, there is no confirmation prompt—it simply deletes everything.
MongoDB does not provide a 'soft delete by default' mechanism—if you delete, data is gone. Best practices to prevent accidents: always double-check the filter before running a wide deleteMany, test the filter with countDocuments first, and consider requiring explicit confirmation in admin tools.
// DANGER: Deletes ALL documents in the collection!
db.users.deleteMany({});
// Before you run deleteMany - always verify your filter first:
// Step 1: Count what will be deleted
const count = await db.collection('users').countDocuments(
{ status: 'temp' } // Your intended filter
);
console.log('Will delete:', count, 'documents');
// Step 2: Only delete after reviewing the count
if (count > 0 && count < SAFE_LIMIT) {
await db.collection('users').deleteMany({ status: 'temp' });
}All lessons in this course
- updateOne and updateMany With $set and $unset
- Increment, Multiply, and Min/Max Operators
- Array Update Operators: $push, $pull, $addToSet
- Deleting Documents Safely With deleteOne and deleteMany