Delete Document in MongoDB

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.
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.
Sample Data
db.employees.insertMany([ { _id:1, firstName: "John", lastName: "King", email: "john.king@abc.com", salary: 5000 }, { _id:2, firstName: "Sachin", lastName: "T", email: "sachin.t@abc.com", salary: 8000 }, { _id:3, firstName: "James", lastName: "Bond", email: "jamesb@abc.com", salary: 7500 }, { _id:4, firstName: "Steve", lastName: "J", email: "steve.j@abc.com", salary: 7000 }, { _id:5, firstName: "Kapil", lastName: "D", email: "kapil.d@abc.com", salary: 4500 }, { _id:6, firstName: "Amitabh", lastName: "B", email: "amitabh.b@abc.com", salary: 7000 } ])
The following deletes a document from the employees
collection.
Example: Delete Single Document using deleteOne()
db.employees.deleteOne({ salary:7000 })
Output
{ 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.
Example: deleteMany()
db.employees.deleteMany({ salary:7000 })
Output
{ acknowledged: true, deletedCount: 2 }
The following deletes all documents where salary
is less than 7000
.
Example: deleteMany()
db.employees.deleteMany({ salary: { $lt:7000} })
Output
{ acknowledged: true, deletedCount: 2 }
If you specify an empty criteria then it will delete all documents in a collection.
Example: Delete All Documents
db.employees.deleteMany({ }) //deletes all documents
Output
{ acknowledged: true, deletedCount: 6 }
Credit: Delete Documents — MongoDB Manual
Average Rating