How do you delete documents in MongoDB?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex MongoDB topics. It also reveals how well you can explain technical ideas to non-experts.
Answer
MongoDB provides three methods to remove documents: deleteOne(): deletes the first document matching the filter. db.users.deleteOne({ _id: ObjectId("...") }). Returns: { acknowledged: true, deletedCount: 1 }. deleteMany(): deletes all documents matching the filter. db.users.deleteMany({ status: "deleted" }). db.users.deleteMany({}) — deletes ALL documents (but keeps the collection and its indexes). findOneAndDelete(): atomically finds, removes, and returns the deleted document. Useful when you need the document's data after deletion (e.g., popping a task from a queue). Soft delete pattern: instead of actually deleting, set a deletedAt field: db.users.updateOne({ _id: id }, { $set: { deletedAt: new Date() } }). Add { deletedAt: { $exists: false } } to all queries. Preserves data for auditing. drop(): removes an entire collection including all documents and indexes: db.users.drop(). Much faster than deleteMany({}) for large collections. dropDatabase(): removes all collections and the database itself: db.dropDatabase(). TTL index for auto-expiry: instead of manual deletion, create a TTL index on a date field: db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }) — MongoDB auto-deletes documents an hour after creation.
Common Mistake
A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.