Q1. How do you delete a single document?
Use deleteOne() to remove the first document that matches the filter:
db.users.deleteOne({ name: "John" })
If multiple documents match, only the first one encountered is deleted (based on natural order).Q2. How do you delete multiple documents?
Use deleteMany() to remove all documents matching the filter:
db.users.deleteMany({ status: "inactive" })
To delete all documents in a collection, pass an empty filter: db.users.deleteMany({})
Q3. How do you drop an entire collection?
Use drop() to delete the collection and its indexes:
db.users.drop()
This is faster than deleteMany({}) because it removes the collection metadata and data files, whereas deleteMany only removes documents.Q4. What happens when you try to delete a non-existent document?
If no document matches the filter, deleteOne() and deleteMany() return an acknowledgment with deletedCount: 0. They do not throw an error. You should check the result object to see if any documents were actually deleted.
Q5. How do you restore deleted documents?
MongoDB does not have a built-in undo for delete operations. To restore, you need backups (mongodump) or point-in-time recovery if using MongoDB Atlas with backups enabled. Always ensure you have a backup strategy before performing mass deletions.
