remove document in mongodb using java

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We have seen insert, find and update operations on mongodb using java. Only remaining is how to remove document in mongodb using java. Let us see an example of it here

Remove Document In Mongodb Using Java:

Just like update functionality, we can reove document in mongodb using java using two methods. i.e. deleteOne and deleteMany where we simply have to pass deletion criteria. Here is what javadoc says about deleteOne

Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not modified.
Parameters:
filter – the query filter to apply the the delete operation
Returns:
the result of the remove one operation

Consider our collection has below documents

now we want to remove document in mongodb using java where salary is less than 50000. We have to create a filter.

  • condition variable specifies the less than condition. This creates a document which simply says < 50000
  • filter variable adds the condition to salary field. It says salary < 50000.

Complete code is as below

Run the program and one document with salary less than 50000 will be deleted. Resultant documents are as below

To remove document in mongodb using java you can also use deleteMany() method which will delete all records matching the filter.

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

2 thoughts on “remove document in mongodb using java

Leave a Reply

Your email address will not be published. Required fields are marked *