MongoDB provides methods to remove documents from collections:
deleteOne()
: Deletes a single document that matches the filter.
Example: db.users.deleteOne({ name: 'John Doe' })
deleteMany()
: Deletes all documents that match the filter.
Example: db.users.deleteMany({ status: 'inactive' })
remove()
: A legacy method that can delete a single document or multiple documents.
Delete all documents in a collection:
db.users.deleteMany({})
Drop an entire collection:
db.users.drop()
Write concern: Specifies the level of acknowledgment requested from MongoDB for write operations. Example:
db.users.deleteMany(
{ status: 'inactive' },
{ writeConcern: { w: 'majority', wtimeout: 5000 } }
)
Delete operations are permanent and cannot be rolled back without a backup.
Best practices: