0 Tk

Deleting Documents

MongoDB provides methods to remove documents from collections:

  1. deleteOne(): Deletes a single document that matches the filter. Example: db.users.deleteOne({ name: 'John Doe' })

  2. deleteMany(): Deletes all documents that match the filter. Example: db.users.deleteMany({ status: 'inactive' })

  3. 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:

  1. Use specific filters to avoid unintended deletions.
  2. Consider soft deletes (updating a ‘deleted’ field instead of removing the document) for data that might need to be recovered.
  3. Ensure proper access controls to prevent unauthorized deletions.
  4. For time-series data or logs, consider using Capped Collections or TTL (Time-To-Live) indexes instead of manual deletions.