We often are required to delete the data that we insert into our database.
Deleting a record or a document in MongoDB is a very common operation that involves removing data from the database. In MongoDB, you can use two methods to delete the record. These are deleteOne() or deleteMany() methods. We can use either of them depending on whether we want to delete a single document or multiple documents from the database that match our criteria.
deleteOne() Method: This method is used when we want to delete a single document from the database. This method takes a query parameter and matches it with all the subsets and whichever record has the same subset value as passed in the query, it gets deleted.
You can add more optional parameters in the options attributes in this method.
await List.deleteOne({task: "hello"});
Code language: CSS (css)
In the above line of code, List is the name of the database. The parameter passed here is the “task” parameter. Mongodb will delete the document whose “task” subset is equal to “hello”. We can pass another parameter separated with the comma that will be considered as the second parameter.
deleteMany() Method: This method is used when we want to delete more than one document from the database. This function also takes the query parameter and deletes all the records that match with the query passed.
const query = { title: { $regex: "Hello" } };
const result = await List.deleteMany(query);
Code language: PHP (php)
In the above code, all the documents where the title subset contains “Hello”, will be deleted.
findOneandDelete()
This is another method to delete the document. It works the same way as the deleteOne() method. The only difference is that this method returns the details of the deleted document. Therefore this method is used when we want to know the deleted document’s data.
let deletedtask = await List.findOneAndDelete({task: “hello”});
console.log(deletedtask);
Code language: JavaScript (javascript)
In this example, the method used first finds the record that matches the query, returns the details of that document, and deletes it.
Conclusion
With this information, you can delete the documents from your MongoDB and use the appropriate methods to do so. This blog talks about 3 deleting methods and all are important to know provided with the specific requirements. You can use the deleteOne() method if a single document is to be deleted or the deleteMany() method if multiple documents are to be deleted.
If you want to delete and want the details of the deleted document, you should use findOneAndDelete(). Hope you got a fair idea on the same.