Signup/Sign In

MongoDB with Java: Retrieve and Delete Document

In this tutorial we will learn how we can retrieve or fetch data from any document stored in a collection and how to delete any existing document stored in any collection.

These functions are equivalent to SELECT and DELETE query in MySQL


Retrieve a Document

If we want to retrieve data against field friends from document with _id xyz123, it can be done with the help of below code snippet:

Retrieve Data in MongoDB


The output produced on console is:

Retrieve Data in MongoDB


Delete a Document

Now, in our friends field, we have data as "andy", "John" and "Amit". If we want to remove "John" from the list, we can with the help of the below code.

Delete Data in MongoDB


The output of the query is:

Delete Data in MongoDB


"John" is removed from the field friends.