There could be situations when you need to remove some records from the database. You may need to delete all the documents or just one or delete some data based on some condition. That's why in this topic we will talk about delete operations in MongoDB.
Delete single document
First of all, let's talk about deleting just one record from our database. For example, we have a collection named employees with such fields: first_name, last_name, and department. Let's fill it with some data:
{first_name: "Ellen", last_name: "Tierney", department: "Development"},
{first_name: "Nick", last_name: "Booker", department: "Design"},
{first_name: "Winston", last_name: "Mccartney", department: "Development"},
{first_name: "Margaret", last_name: "Roberson", department: "Design"}
So, imagine that one of our employees, Nick, was fired (none of the employees were actually fired during this example). This means, that we need to remove him from the database. MongoDB has the deleteOne() command just for our case. It has the following syntax:
db.<collection>.deleteOne({<condition>})
Let's use it on our collection:
db.employees.deleteOne({first_name: "Nick", last_name: "Booker"})
After executing this command, our employees collection will look like this:
{first_name: "Ellen", last_name: "Tierney", department: "Development"},
{first_name: "Winston", last_name: "Mccartney", department: "Development"},
{first_name: "Margaret", last_name: "Roberson", department: "Design"}
As you can see, the designated employee was successfully removed from our collection.
deleteOne() will remove only the first of them. Delete multiple documents
Now let's talk about removing several documents from a collection. As you may have guessed, MongoDB has the deleteMany() method for that. For the next example, we will take our entire previous collection. This time imagine that the Development department created their own database and they have inserted all the developers there. So we need to remove them from our database. We will use the following expression:
db.employees.deleteMany({department: "Development"})
Now our collection looks like this:
{first_name: "Nick", last_name: "Booker", department: "Design"},
{first_name: "Margaret", last_name: "Roberson", department: "Design"}
Records about all the developers were deleted as we wanted.
The deleteMany() command removes all the records that match the set condition. So, if you do not specify a condition, all the data will be deleted. To delete all the data from the collection, use this command: db.<collection>.deleteMany({}).
Conclusion
In this rather small topic you have learned about two MongoDB methods that will help you delete some data:
deleteOne()to delete just one record.deleteMany()to delete multiple records.
Now it is time to put your knowledge into practice!