Video Transcript (English)
Hello!
In this video, you will learn how to use the deleteOne() and deleteMany() methods in the Filters builder class for a Java application using MongoDB as its backing database.
You can delete a single document from a collection by using the deleteOne() method from a MongoCollection instance.
For brevity, we’ll assume that we have already instantiated the MongoClient and MongoCollection instances.
The deleteOne() method accepts a query filter that matches the document that you want to delete. It returns an instance of a DeleteResult,which contains information about how many documents were deleted.
The following code deletes a single document from the accounts collection in the accounts database. This example uses the Filters builder class method, eq(), to match an account belonging to “John Doe”. Then, the deleteOne() method is called to delete John Doe’s account. To confirm it was deleted, we print out the count of the number of deleted documents.
If the deleteOne()method is called with an empty query filter document, it deletes the first document that matches the filter, but not all documents that might match the filter.
To delete multiple documents from a collection in a single operation, we use the MongoCollection's deleteMany() method.
The deleteMany() method accepts a query filter that matches the documents to be deleted. After the documents are deleted, the method returns an instance of DeleteResult, which enables the retrieval of information such as the number of documents that were deleted.
If the deleteMany() method is invoked with an empty query filter document, then all documents in the collection will be deleted.
Suppose we want to delete all dormant accounts. In this case, we will invoke the deleteMany() method with a query filter for all accounts with an account status of dormant.
Then we’ll print the number of deleted accounts.
Well done!
You now know how to delete documents from a MongoDB collection by using the deleteOne() and deleteMany() methods with query filters. Don’t forget that deleteMany() with an empty query will delete all documents.