Open In App

Dynamic Query in Java Spring Boot with MongoDB

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:
Project 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.

Database


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

name

Rohith

age

23

email

[email protected]

Click on the "Send" button to fetch the users from database. Consider below images.

Postman Request:

API call
API Call


Postman Response:

Output

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.


Next Article

Similar Reads