0% completed
Delete operations in MongoDB allow you to remove documents from a collection. These operations are crucial for managing and maintaining the integrity of your data by enabling you to remove outdated, irrelevant, or incorrect data.
MongoDB provides several methods for deleting documents:
deleteOne()
deleteMany()
remove()
.Understanding these methods and how to use them effectively is essential for efficient data management in MongoDB.
The deleteOne()
method is used to delete a single document that matches the specified filter. If multiple documents match the filter, only the first one encountered is deleted. This method is part of MongoDB's new CRUD API introduced in version 3.2 and is designed for precise control over single-document deletions.
db.collection.deleteOne( <filter>, <options> )
Delete a Document by a Specific Field
db.users.deleteOne({ name: "Alice" })
This command deletes the first document where the name
is "Alice".
Delete a Document by ID
db.users.deleteOne({ _id: ObjectId("507f1f77bcf86cd799439011") })
This command deletes the document with the specified _id
.
The deleteMany()
method is used to delete all documents that match the specified filter. This method is efficient for bulk deletions and ensures that all matching documents are removed from the collection.
db.collection.deleteMany( <filter>, <options> )
Delete Multiple Documents by a Specific Field
db.users.deleteMany({ age: { $lt: 30 } })
This command deletes all documents where the age
field is less than 30.
Delete Multiple Documents by a Nested Field
db.users.deleteMany({ "address.city": "Old City" })
This command deletes all documents where the city
field of the address
object is "Old City".
The remove()
method is an older method used to delete documents from a collection. It can delete either a single document or multiple documents depending on the justOne
option. While still supported, it has been largely replaced by deleteOne()
and deleteMany()
in modern applications.
db.collection.remove( <filter>, <options> )
Delete a Single Document
db.users.remove({ name: "Alice" }, { justOne: true })
This command deletes the first document where the name
is "Alice".
Delete Multiple Documents
db.users.remove({ age: { $gte: 30 } })
This command deletes all documents where the age
field is greater than or equal to 30.
.....
.....
.....