MongoDb - deleting data in MongoDB
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" })
-
Removes the first document where
name = "Alice"
.
b) Delete Multiple Documents
db.users.deleteMany({ age: { $lt: 25 } })
-
Removes all users younger than 25.
c) Delete All Documents in a Collection
db.users.deleteMany({})
-
Removes everything inside
users
collection, but keeps the collection itself.
d) Drop a Collection
db.users.drop()
-
Completely removes the
users
collection (including indexes).
e) Drop a Database
db.dropDatabase()
-
Deletes the entire current database and all its collections.
3. Return Value
Both deleteOne()
and deleteMany()
return a result object:
Example:
{ "acknowledged": true, "deletedCount": 3 }