Advanced Search and Filtering API Using Spring Data and MongoDB
In this tutorial, you will learn to implement filter/search Rest API for an existing Spring Boot application using Spring Data JPA and MongoDB.
Join the DZone community and get the full member experience.Join For Free
It is common to have to perform complex searches in our API in production mode. Too much duplicate code has to be written to perform simple queries on each document.
Spring Data offers the ability to perform simple or complex queries on MongoDB documents.
In this tutorial, we will focus on dynamically building search and paging queries in MongoDB.
- Spring Boot 2.4
- Maven 3.6.+
- Java 8+
- Mongo 4.4
We will start by creating a simple Spring Boot project from start.spring.io, with the following dependencies: Web, MongoDB, and Lombok.
Here is our project structure:
To get started, we need a model class. For this tutorial, we have an
Employeemodel class in which the
Department class is embedded.
We now have the common
ResourceRepository interface which extends from
MongoRepository and will include all custom methods.
EmployeeRepository will be extended to
ResourceRepository. This will allow it to inherit the implicit methods provided by Spring Mongo Repository and
Query classes provide a way to query MongoDB with Spring Data by centralizing typed queries, which helps us avoid syntax errors.
We have, therefore, created a generic class,
GenericFilterCriteriaBuilder, which will take care of building all the requests before sending them to Spring Data.
Suppose we have the «employee» collection with all the documents like this:
This is the structure of the server-side pagination result from the APIs:
For each paging endpoint we have the following Params:
- page=0: page index (default value 0)
- size=20: page size (default value 20)
- filterAnd= : And filters conditions (e.g. lastName|eq|john)
- filterOr= : Or filters conditions (e.g. lastName|eq|john)
- orders= : filters Orders
* replace | by the code %7C
- Get all the employees of the IT department order by
- Get all the employees of IT and TS (technical support team) order by
- Get the first five employees ordered by name:
- Get all the employees whose email contains .edu:
And we're done.
In this post, we have learned how to implement a filter/search REST API in a Spring Boot application using Spring Data JPA and MongoDB.
Full source code can be found on GitHub.
Opinions expressed by DZone contributors are their own.