1. Methods for Deletion
MongoDB provides three main ways to delete data:
-
deleteOne(filter, options)
→ deletes the first matching document.
-
deleteMany(filter, options)
→ deletes all documents that match the filter.
-
db.collection.drop()
→ deletes the entire collection (all documents + metadata).
2. Examples
a) Delete One Document
db.users.deleteOne({ name: "Alice" })
b) Delete Multiple Documents
db.users.deleteMany({ age: { $lt: 25 } })
c) Delete All Documents in a Collection
db.users.deleteMany({})
d) Drop a Collection
db.users.drop()
e) Drop a Database
db.dropDatabase()
3. Return Value
Both deleteOne() and deleteMany() return a result object:
Example:
{ "acknowledged": true, "deletedCount": 3 }