DEV Community

Cover image for MongoDB - Aggregations with Java + Spring
Arturo Batistute
Arturo Batistute

Posted on

MongoDB - Aggregations with Java + Spring

Coming from PostgreSQL, one of the first things I noticed when I started working with MongoDB was the lack of built-in query methods like those provided by JpaRepository. With MongoRepository, we often only get the basic findAll() method by default.

This post will guide you through creating Aggregations (custom queries) to overcome these limitations. It mirrors the functionality of the Aggregation Pipeline in MongoDB Atlas, but implemented on the Java side using Spring Data MongoDB.

In the aggregation pipeline, you list out a series of instructions in a "stage." For each stage that's defined, MongoDB executes them one after another in order to give a finalized output you're able to use.


Pre-considerations

We'll use a sample dataset provided by MongoDB and map a Java class to some of its fields.

Airbnb sample data

In our class we will use the @Document with our collection name.

Java entity class mapping some fields that we have in the sample data

In the service layer, we have a method that will call our repository and pass a string that will be the filter for our query.

Service class that will call the find method using the injected repository class


Custom Repository

Create a custom repository where we can set our custom queries and we will extend this interface in the main @Repository interface. The goal is to keep the repository access centralized in one single place.

Custom repository class with custom methods

Main repository class that extends our custom class

For the custom query we use the MongoTemplate helper class to execute our query that will come with the filter.

With this class you can:

  • Perform CRUD operations (Create, Read, Update, Delete)
  • Execute queries
  • Work with indexes
  • Handle collections
  • Convert between Java objects and MongoDB documents (using MappingMongoConverter)

In this example we used the .regex to find an specific word inside both "name" and "summary" fields. I suggest you try for yourself to explore the diverse possibilities that the Query class can offer.

Repository implementation class that uses the MongoTemplate to create the aggregation

Description:

  • Pattern.quote(...): escapes any special regex characters in the user input (also prevents regex injection).

  • "i": makes it case-insensitive.

To conclude, to create an aggregation you will need to create a Query and build a Criteria with the specific filters.


Result

In this test we searched for the word "duplex" and after executing, we can see that the aggregation worked fine:

Postman image showing database results with the filtered text

Any problems or suggestions, feel free to get in touch.

All the best!

Resources:

https://www.mongodb.com/resources/products/capabilities/aggregation-pipeline

Top comments (0)