Deleting Documents in MongoDB: A Comprehensive Guide
Learn how to effectively remove documents from MongoDB collections using the deleteOne()
and deleteMany()
methods. This guide will provide you with the necessary knowledge and examples to perform document deletion operations in your MongoDB applications.
MongoDB: Delete Documents in a Collection
MongoDB offers methods to delete documents from a collection. You can use deleteOne()
to delete the first matching document or deleteMany()
to delete all matching documents.
Delete One Document
Use db.collection.deleteOne()
to delete the first document that matches the filter criteria.
Syntax
db.collection.deleteOne(filter, options)
Parameters:
filter
: Criteria to match documents, similar tofind()
method.options
: Optional. IncludeswriteConcern
,collation
, andhint
.
Insert sample documents into the employees
collection:
Sample Data
db.employees.insertMany([
{ _id: 1, firstName: "John", lastName: "Doe", email: "john.doe@example.com", salary: 5000 },
{ _id: 2, firstName: "Jane", lastName: "Smith", email: "jane.smith@example.com", salary: 8000 },
{ _id: 3, firstName: "Emily", lastName: "Johnson", email: "emily.johnson@example.com", salary: 7500 },
{ _id: 4, firstName: "Michael", lastName: "Brown", email: "michael.brown@example.com", salary: 7000 },
{ _id: 5, firstName: "Sarah", lastName: "Davis", email: "sarah.davis@example.com", salary: 4500 },
{ _id: 6, firstName: "David", lastName: "Wilson", email: "david.wilson@example.com", salary: 7000 }
])
Example: Delete a Single Document
Syntax
db.employees.deleteOne({ salary: 7000 })
Output
{ acknowledged: true, deletedCount: 1 }
Delete Many Documents
Use db.collection.deleteMany()
to delete all documents matching the filter criteria.
Syntax
db.collection.deleteMany(filter, options)
Parameters:
filter
: Criteria to match documents, similar tofind()
method.options
: Optional. IncludeswriteConcern
,collation
, andhint
.
Example: Delete Documents with Salary 7000
Syntax
db.employees.deleteMany({ salary: 7000 })
Output
{ acknowledged: true, deletedCount: 2 }
Example: Delete Documents with Salary Less than 7000
Syntax
db.employees.deleteMany({ salary: { $lt: 7000 } })
Output
{ acknowledged: true, deletedCount: 2 }
Example: Delete All Documents
Syntax
db.employees.deleteMany({})
Output
{ acknowledged: true, deletedCount: 6 }