MongoDB: Delete Documents in a Collection
MongoDB provides the following methods to delete one or more documents in a collection.
- db.collection.deleteOne() - Deletes the first matching document in a collection.
- db.collection.deleteMany() - Deletes all the matching documents in a collection.
db.collection.deleteOne()
Use the db.<collection>.deleteOne()
method to delete the first documents that match with the specified filter criteria in a collection.
Syntax:
db.collection.deleteOne(filter, options)
Parameters:
- filter: The selection criteria for the update, same as find() method.
- options: Optional. May contains options for update behavior. It includes writeConcern, collation, and hint parameters.
In the above syntax, db
points to the current database, <collection>
points is an existing collection name.
To demonstrate the delete operation, insert the following sample documents in the employees
collection.
db.employees.insertMany([
{
_id:1,
firstName: "John",
lastName: "King",
email: "[email protected]",
salary: 5000
},
{
_id:2,
firstName: "Sachin",
lastName: "T",
email: "[email protected]",
salary: 8000
},
{
_id:3,
firstName: "James",
lastName: "Bond",
email: "[email protected]",
salary: 7500
},
{
_id:4,
firstName: "Steve",
lastName: "J",
email: "[email protected]",
salary: 7000
},
{
_id:5,
firstName: "Kapil",
lastName: "D",
email: "[email protected]",
salary: 4500
},
{
_id:6,
firstName: "Amitabh",
lastName: "B",
email: "[email protected]",
salary: 7000
}
])
The following deletes a document from the employees
collection.
db.employees.deleteOne({ salary:7000 })
{ acknowledged: true, deletedCount: 1 }
The above command deletes the first matching document even if multiple documents match with the specified criteria.
deleteMany()
Use the db.<collection>.deleteMany()
method to delete all the documents that match with the specified filter criteria in a collection.
Syntax:
db.collection.deleteMany(filter, options)
Parameters:
- filter: The selection criteria for the update, same as find() method.
- options: Optional. May contains options for update behavior. It includes writeConcern and collation, and hint parameters.
The following deletes all documents from the employees
collection that match with the specified criteria.
db.employees.deleteMany({ salary:7000 })
{ acknowledged: true, deletedCount: 2 }
The following deletes all documents where salary
is less than 7000
.
db.employees.deleteMany({ salary: { $lt:7000} })
{ acknowledged: true, deletedCount: 2 }
If you specify an empty criteria then it will delete all documents in a collection.
db.employees.deleteMany({ }) //deletes all documents
{ acknowledged: true, deletedCount: 6 }