Skip to main content

MongoDB fetch operation using Java API

With changes in MongoDB, there has been several changes in its Java API as well. There are now some good and easy way to perform different operation with DB.

MongoDB Java API is really very simple and easy to understand. If we understand the basics, we can build up simple to complex queries.

Let's take a look at the example of MongoDB fetch operation using the new Java API and then we'll try to understand the basics..


public MyEntity findMyEntityById(long entityId) {

    List<Bson> queryFilters = new ArrayList<>();
    queryFilters.add(Filters.eq("_id", entityId));
    Bson searchFilter = Filters.and(queryFilters);
    //Fields to return. 
    //_id is available by default. A value of "0" would skip it
    List<Bson> returnFilters = new ArrayList<>();
    returnFilters.add(Filters.eq("name", 1));
    returnFilters.add(Filters.eq("_id", 0)); //Only if don't need _id in response
    Bson returnFilter = Filters.and(returnFilters);

    //Perform Fetch operation
    Document doc = getMongoCollection().find(searchFilter).projection(returnFilter).first();
    //Deserialize the document into the Entity object
    JsonParser jsonParser = new JsonFactory().createParser(doc.toJson());
    ObjectMapper mapper = new ObjectMapper();

    MyEntity myEntity = mapper.readValue(jsonParser, MyEntity.class);
    return myEntity;
}

What all we need to do is to prepare following things:

  • queryFilter: criteria to filter records. Like where clause in SQL
  • returnFilter: This is known as projection in MongoDB terms. This filter represents all we need in return from fetch operation. Specify the fields that you need or just skip it all if you need all, based on your requirement or performance considerations.


Once you get the records as Document, you can further use Jackson to de-serialize it to the related Entity object.

Comments