Dynamic Query in Java Spring Boot with MongoDB
Last Updated :
13 Aug, 2024
Most of today’s applications require great flexibility regarding database querying. MongoDB provides an effective option for solving complex queries using this kind of storage for documents. Integrating it with Spring Boot makes things even smoother. In this article, we will look at how to create dynamic queries in a Spring Boot application using MongoDB.
Prerequisites:
Make sure the following have been done before you begin:
- Java Development Kit (JDK)
- MongoDB: Ensure MongoDB is properly installed and running on your machine. You may choose to use MongoDB Compass, a graphical user interface (GUI) tool that helps you manage and visualize your databases in MongoDB.
Implementation of Dynamic Query in Java Spring Boot with MongoDB
Step 1: Set Up a Spring Boot Project
Launch your preferred Integrated Development Environment (IDE) like IntelliJ IDEA, Eclipse, or Spring Tool Suite (STS).
Create a new Spring Boot project using Spring Initializr:
- Go to Spring Initializr.
- Choose the necessary project settings such as Group, Artifact, and dependencies. Choose dependencies including “Spring Web” to build RESTful APIs with Spring MVC.
- Add the following dependencies in
pom.xml
:
XML
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- To download the project ZIP file, click on “Generate”.
- Extract the zipped file which has been downloaded and open it in your IDE.
- Below is the project directory structure:
Step 2: Define Your MongoDB Document
We are going to create a very basic MongoDB document. Let us assume, for example purposes, that we are dealing with User entity.
Java
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "users")
public class User {
@Id
private String id;
private String name;
private int age;
private String email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Step 3: Create a Repository Interface
The spring data mongodb gives you a good repository interface which you can base on while making database queries. Create your repository interface extending MongoRepository.
Java
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends MongoRepository<User, String>, UserRepositoryCustom {
}
Step 4: Custom Repository for Dynamic Queries
In order to achieve dynamic queries, we need to build some custom repositories. These include developing custom interfaces and their implementations.
Custom Interface:
Java
import java.util.List;
public interface UserRepositoryCustom {
List<User> findUsersByCriteria(String name, Integer age, String email);
}
Implementation:
Java
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
@Value("${spring.data.mongodb.database}")
private String databaseName;
@Override
public List<User> findUsersByCriteria(String name, Integer age, String email) {
MongoDatabase database = MongoClients.create().getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection("users");
Document query = new Document();
if (name != null && !name.isEmpty()) {
query.append("name", name);
}
if (age != null) {
query.append("age", age);
}
if (email != null && !email.isEmpty()) {
query.append("email", email);
}
List<User> users = new ArrayList<>();
for (Document doc : collection.find(query)) {
User user = new User();
user.setId(doc.getObjectId("_id").toString());
user.setName(doc.getString("name"));
user.setAge(doc.getInteger("age"));
user.setEmail(doc.getString("email"));
users.add(user);
}
return users;
}
}
Step 5: Use of Custom Repository
When you have done everything, then you can use the custom repository in your controller or service for dynamic queries processing.
Service Layer:
Java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getUsersByCriteria(String name, Integer age, String email) {
return userRepository.findUsersByCriteria(name, age, email);
}
}
Controller Layer:
Java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getUsers")
public List<User> getUsers(
@RequestParam(required = false) String name,
@RequestParam(required = false) Integer age,
@RequestParam(required = false) String email) {
return userService.getUsersByCriteria(name, age, email);
}
}
Step 6: Configure Application Properties
Open the src/main/resources/application.properties file and configure your application properties:
# Application name
spring.application.name=mongodb
# MongoDB host (local machine)
spring.data.mongodb.host=localhost
# MongoDB port (default 27017)
spring.data.mongodb.port=27017
# MongoDB database name
spring.data.mongodb.database=FirstDB
Step 7: Add Data in Database
We need data in our MongoDB database to demonstrate dynamic queries. The following screenshot displays the users collection with test data inserted in it.
Postman Testing Process for getUsers API
Let's walk through the steps to find Users from database using the getUsers endpoint.
- Method: GET
- URL: http://localhost:8080/getUsers
- Add key and value in Params section as given below
Click on the "Send" button to fetch the users from database. Consider below images.
Postman Request:
API Call
Postman Response:
Conclusion
Creating dynamic queries in Spring Boot application with MongoDB is not complicated at all. With spring data’s repository abstraction and mongoDB’s flexible query capabilities, powerful and efficient query mechanisms suited to your application specific needs can be created.
Similar Reads
Spring Boot JPA Native Query with Example
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any Java object directly into a database table. A native query is a SQL statement that is specific to
7 min read
Spring Boot Integration With MongoDB as a Maven Project
MongoDB is a NoSQL database and it is getting used in software industries a lot because there is no strict schema like RDBMS that needs to be observed. It is a document-based model and less hassle in the structure of the collection. In this article let us see how it gets used with SpringBoot as a Ma
4 min read
Loading Initial Data with Spring Boot
Loading initial data into a Spring Boot application is a common requirement for seeding the database with predefined data. This data could include reference data, default settings, or simple records to populate the application upon startup. The main concept involves using Spring Boot's data initiali
3 min read
Adding and Querying the Data in MongoDB
In MongoDB, data is stored in BSON format within collections. This guide covers the essential steps for adding and querying data in MongoDB, including creating collections, inserting single and multiple documents and using various query operators to filter data. In this article, We will learn about
5 min read
Spring Boot JpaRepository with Example
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
9 min read
Spring Data JPA @Query Annotation with Example
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any Java object directly into a database table. @Query Annotation is used for defining custom queries
7 min read
Spring Boot JPA Sample Maven Project With Query Methods
In this article, let us see a sample maven project in Spring Boot JPA with Query methods. Spring Boot + JPA removes the boilerplate code and it will be enhanced much if we use query methods as well. Let us discuss this project with MySQL Connectivity for geeksforgeeks database and table name as "Con
6 min read
Spring Boot - CRUD Operations using MongoDB
CRUD stands for Create, Read/Retrieve, Update, and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods. HTTP has a few methods which work as CRUD operations and do note they are very vital from a develo
5 min read
Spring Boot with H2 Database
H2 Database in Spring Boot is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk. Here we will be discussing how can we configure and perform some b
6 min read
Spring Boot - OAuth2 with JWT
OAuth 2.0 is defined as Open Authorization (Version 2.0), and it is a widely used authorization framework that can be used by third-party applications to gain limited access to a user's HTTP service, which means allowing the specified user to allow the third-party application to obtain access on its
15+ min read