Deleting Documents
deleteOne, deleteMany, and safe deletion patterns
Skills taught: mongodb.crud-delete
Delete Methods
MongoDB provides three deletion methods: deleteOne() removes the first document that matches the filter, deleteMany() removes all matching documents, and findOneAndDelete() atomically removes and returns the deleted document.
const products = db.collection('products');
// Delete one matching document
const r1 = await products.deleteOne({ name: 'Old Widget' });
console.log('Deleted:', r1.deletedCount); // 0 or 1
// Delete all out-of-stock products
const r2 = await products.deleteMany({ inStock: false });
console.log('Deleted:', r2.deletedCount, 'documents');
// Delete with more complex filter
const oneMonthAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const r3 = await sessions.deleteMany({
expiresAt: { $lt: new Date() } // delete all expired sessions
});
// Delete by ID
const { ObjectId } = require('mongodb');
await products.deleteOne({ _id: new ObjectId('6752ab3f1234567890abcdef') });
// findOneAndDelete — atomically remove and return the document
const deleted = await tasks.findOneAndDelete(
{ status: 'completed' },
{ sort: { completedAt: 1 } } // remove oldest completed task first
);
if (deleted) console.log('Archived task:', deleted.title);
Warning: deleteMany({}) deletes ALL documents in the collection. The empty filter {} matches everything. Always double-check your filter before running deleteMany() in production.
Dropping Collections and Databases
// Drop a collection — removes all documents AND all indexes
await db.collection('temp_data').drop();
// Drop an entire database — removes all collections and data
await client.db('old_project').dropDatabase();
// Drop is IRREVERSIBLE — no recycle bin, no undo!
// Always back up before dropping in production.
// In mongosh:
db.temp_data.drop() // drop collection
db.dropDatabase() // drop current database
Soft Delete Pattern (Recommended in Production)
In production applications, hard deletes are rarely the right choice. Instead, use a soft delete: add a deletedAt timestamp and filter it out in queries. This gives you an audit trail, allows recovery, and supports compliance requirements like GDPR data retention periods.
// Soft delete: mark as deleted without removing the document
await users.updateOne(
{ _id: userId },
{ $set: { deletedAt: new Date(), deletedBy: adminId } }
);
// In all queries, filter out deleted records
const activeUsers = await users.find({
deletedAt: { $exists: false } // only undeleted users
}).toArray();
// Or use $eq: null (works for both missing field and null value)
const activeUsers2 = await users.find({
deletedAt: null
}).toArray();
// Restore a soft-deleted record
await users.updateOne(
{ _id: userId },
{ $unset: { deletedAt: '', deletedBy: '' } }
);
// Hard delete after retention period (GDPR compliance)
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
await users.deleteMany({
deletedAt: { $lt: thirtyDaysAgo }
});
Tip: Create a partial index on deletedAt for efficient queries: db.users.createIndex({ email: 1 }, { partialFilterExpression: { deletedAt: { $exists: false } } }). This index only covers active (non-deleted) users.
TTL Indexes for Auto-Expiry
A TTL (Time To Live) index automatically deletes documents after a specified duration. Perfect for sessions, caches, temporary verification codes, and log retention.
// Create a TTL index: delete sessions 24 hours after createdAt
await sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 86400 } // 86400 seconds = 24 hours
);
// Now just insert normally — MongoDB auto-deletes after 24h
await sessions.insertOne({
userId: userId,
token: generateToken(),
createdAt: new Date() // TTL field
});
// For exact expiry time, use expiresAt field
await sessions.createIndex(
{ expiresAt: 1 },
{ expireAfterSeconds: 0 } // expire AT the expiresAt time
);
await sessions.insertOne({
userId: userId,
token: generateToken(),
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 7 days from now
});
MongoDB's TTL background thread runs every 60 seconds, so there is a slight delay between when a document expires and when it is actually deleted. Don't rely on TTL for precise second-level expiry.
Hard Delete vs Soft Delete
- Hard Delete: Permanently remove the document from the collection
- Soft Delete: Mark as deleted with deletedAt timestamp, keep the document
Frequently Asked Questions
How do I drop an entire collection?
Use collection.drop(). This removes all documents, all indexes, and the collection metadata. It is irreversible — there is no recycle bin. Always back up before dropping a production collection.
Can I recover a deleted document?
No — hard deletes in MongoDB are permanent unless you have a backup. This is why soft deletes (marking with deletedAt) are preferred in production. If you have an Atlas backup or a replica set oplog, you may be able to restore from there, but it's complex.
How do I delete old data automatically?
Use a TTL index: createIndex({ createdAt: 1 }, { expireAfterSeconds: N }). MongoDB automatically deletes documents where createdAt is older than N seconds. The background job runs every 60 seconds.