You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
MongoDB provides two primary methods for removing documents: deleteOne and deleteMany. Both accept the same filter objects you already know from find and update.
deleteOne removes the first document that matches the filter. It is the safest deletion method when you are targeting a specific record.
// Delete the user with this specific email
db.users.deleteOne({ email: "bob@example.com" })
The result object includes deletedCount — the number of documents actually removed (0 or 1 for deleteOne).
{ acknowledged: true, deletedCount: 1 }
deleteMany removes all documents matching the filter. Use it carefully — a broad filter can wipe large amounts of data.
// Remove all sessions that expired more than 30 days ago
const cutoff = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
db.sessions.deleteMany({ expiresAt: { $lt: cutoff } })
Calling deleteMany with an empty filter {} deletes every document in the collection. Always double-check your filter before running bulk deletes.
findOneAndDelete removes the document and returns it in a single atomic operation. This is useful when you need to process or log the document before it disappears.
const removed = db.jobs.findOneAndDelete(
{ status: "pending" },
{ sort: { createdAt: 1 } } // process oldest first
)
console.log("Processed job:", removed)
If you want to remove all documents and the collection itself, use drop:
db.tempLogs.drop()
drop also removes all indexes on the collection, which is faster than deleteMany({}) for large collections because it does not scan individual documents.
In production systems it is common to use a soft delete pattern instead of permanently removing data. Instead of calling deleteOne, you set a deletedAt timestamp:
db.orders.updateOne(
{ _id: orderId },
{ $set: { deletedAt: new Date() } }
)
All queries then filter with { deletedAt: { $exists: false } } to exclude soft-deleted records. This approach preserves an audit trail and allows data recovery.
When a delete must be coordinated with other writes (for example, removing a user and all their orders), wrap everything in a multi-document transaction:
const session = client.startSession()
session.withTransaction(async () => {
await db.users.deleteOne({ _id: userId }, { session })
await db.orders.deleteMany({ userId }, { session })
})
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.