You are here
Home > java >

Spring Data MongoDB Tutorial

Spring Data MongoDB TutorialIn today’s data-motivated world, it becomes very crucial to manage and query huge volumes of data efficiently for businesses to stay competitive. MongoDB, a popular NoSQL database, offers flexibility and scalability. On the other hand, Spring Data provides a powerful framework for simplifying data management in Java applications. The term ‘Spring Data MongoDB’ is nothing, but it is a combination of both ‘Spring Data’ and ‘MongoDB’. In simple words, Spring Data MongoDB is a small readymade project provided by Spring community, that simplifies the process of how a Spring based application interacts with MongoDB, a NoSQL database.

In this article, we will explore the world of Spring Data MongoDB, investigating its features, benefits, and practical examples to help you utilize its full capability.

Table of Contents

What is Spring Data MongoDB?

Spring Data MongoDB is part of the Spring Data umbrella project. In simple words, we can understand it as a subset of broader Spring Data. Spring Data is intended to provide a compatible and easy-to-use way to work with different databases from the Spring Framework. In case of MongoDB, it is known as Spring Data MongoDB, especially dedicated to MongoDB. Spring Data MongoDB eliminates boilerplate code and simplifies database interactions by providing high-level abstractions and utilities.

Key Features of Spring Data MongoDB

Some important fey features of Spring Data MongoDB are:

POJO (Plain Old Java Object) Mapping

Spring Data MongoDB maps Java objects to MongoDB document. It offers developers to work with familiar Java classes rather than dealing with low-level database operations.

Repository Support

Spring Data MongoDB offers repository support, which facilitates developers to perform CRUD (Create, Read, Update, Delete) operations on MongoDB collections using familiar methods such as save(), findById(), findAll(), and delete().

Query DSL (Domain-Specific Language)

Query DSL feature of Spring Data MongoDB offers developers to express complex queries in a concise and readable syntax, making it easier to retrieve data from MongoDB collections.

Pagination and Sorting

Spring Data MongoDB simplifies pagination and sorting of query results by offering developers to handle large datasets in the simplest way.

Index Management

We can define and manage MongoDB indexes using annotations or XML configuration, optimizing query performance and ensuring scalability.

Auditing

Spring Data MongoDB supports auditing of documents, automatically populating fields such as creation date, last modified date, and user information.

Custom Query Methods

We can define custom query methods in repository interfaces. We can utilize Spring Data MongoDB’s method naming conventions to generate MongoDB queries automatically.

How to work with Spring Data MongoDB?

After getting a basic theoretical understanding, let’s talk about practical things and do some exercise.

Tools & Technologies used in this example

♦ STS (Spring Tool Suite) : Version-> 4.7.1.RELEASE
⇒ Dependent Starters : ‘Spring Boot Mongodb’, and ‘Lombok’
♦ JDK8 or later versions (Extremely tested on JDK8, JDK11, JDK14, and JDK17)
♥ MongoDB 3.6.20 2008R2Plus SSL (64 bit)

Now, let’s create a Spring Boot Project using Spring Data MongoDB step by step.

Step#1: Create a Spring Boot Starter Project and add MongoDB dependency

There are multiple ways to create project and add MongoDB dependency.

Step#1A: Using Java IDE STS(Spring Tool Suite)

We have used STS as an IDE to create these examples. While creating Starter Project select ‘Spring Data MongoDB’ as starter project dependencies. Optionally, if you are interested to use Lombok, also select ‘Lombok’ as another dependency. We are not using Lombok here for the sake of keeping thing simple & easy to understand.

Still, if you don’t know how to create Spring Boot Starter Project, Kindly visit a separate article on how to create a project using STS?.

You may visit about Lombok in order to know how to configure it and other detailed concepts of it.

Step#1B: Using Spring Initializr 

We can use Spring Initializr to get readymade starter project. While generating project, add dependency ‘Spring Data MongoDB’, and use any IDE to import your project.

Step#1C: Manually By Adding Dependency

If you are using any other IDE which doesn’t support adding dependencies at runtime, you can add dependency manually.

If you are using Maven, you can add the following dependencies to your pom.xml file:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Step#2: Update application.properties

Update application.properties by adding below entries:

spring.data.mongodb.host=localhost 
spring.data.mongodb.port=27017 
spring.data.mongodb.database=testMongoDB

Once we have added the dependencies, we can define our MongoDB entities as POJOs and repositories as interfaces extending MongoRepository. Let’s go through an example:

Step#3: Start MongoDB 

To work with MongoDB, check if you have installed the Mongo DB in your system. If not, please visit our article on how to download and install MongoDB in your system. Here, you will find step by step tutorial to download & install MongoDB including some required commands to operate on it.

We need to Start MongoDB server then start MongoDB client by typing below commands on two command prompts separately.
->Start Mongo Server : cmd > mongodb
->Start Mongo Client  : cmd > mongo

Step#4: Create Entity class Book.java

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "books")
public class Book {

   @Id
   private String id;
   private String title;
   private String author;
   private int pages;

   // Getters and setters

}

Step#5: Create Repository interface BookRepsitory.java

import org.springframework.data.mongodb.repository.MongoRepository;

public interface BookRepository extends MongoRepository<Book, String> {

   List<Book> findByAuthor(String author);

   List<Book> findByPagesGreaterThan(int pages);

}

In the above example, we defined a Book entity with annotations for MongoDB mapping. We also created a BookRepository interface that extends MongoRepository, providing methods for querying books by author and pages.

How to use Spring Data MongoDB in our Application?

As we have our entities and repositories defined, let’s see how we can use them in our application:

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    public void saveBook(Book book) {
        bookRepository.save(book);
    }

    public List<Book> findBooksByAuthor(String author) {
        return bookRepository.findByAuthor(author);
    }

    public List<Book> findBooksByPagesGreaterThan(int pages) {
        return bookRepository.findByPagesGreaterThan(pages);
    }
}

In the BookService class, we injected the BookRepository bean and use its methods to save books and retrieve books by author or pages.

Multiple Ways of Working with MongoDB in Spring Boot

Here we will discuss three common ways of working in Spring Boot with MongoDB.

These are using MongoRepository, @Query annotation, and MongoTemplate. Let’s explore these three ways and compare them with examples.

1) Using MongoRepository

This is the most common & popular way of working in Spring Boot with MongoDB. MongoRepository is part of Spring Data MongoDB.

  • It offers a high-level abstraction for creating CRUD operations on MongoDB collections without writing explicit queries.
  • It allows us to create custom repository interfaces by extending MongoRepository<T, ID>, where T is the entity type and ID is the type of the entity’s primary key.
  • Spring Data MongoDB generates queries based on method names.

For example, consider the below code:

public interface BookRepository extends MongoRepository<Book, String> {

   List<Book> findByAuthor(String author);

   List<Book> findByPagesGreaterThan(int pages);

}

In this example, findByAuthor() and findByPagesGreaterThan() methods are automatically translated into MongoDB queries to find books by author and pages, respectively. MongoRepository abstracts away the complexities of query creation, making it easy to perform common operations.

For complete CRUD operations using MongoRepository including mutiple examples, kindly visit a separate article on Spring Boot MongoDB CRUD Examples.

2) Using @Query Aannotation

@Query annotation allows us to define custom MongoDB queries using MongoDB’s query language within repository interfaces or service classes. This approach provides flexibility to execute complex queries that cannot be created using method naming conventions.

  • Using @Query annotation, we can define custom queries directly in our repository interface.
  • It allows us to write MongoDB-specific queries using the MongoDB query language.

For example: Let’s say we want to find books by author and pages greater than a specified value:

public interface BookRepository extends MongoRepository<Book, String> {

    @Query("{ 'author' : ?0 }")
    List<Book> findBooksByAuthor(String author);

    @Query("{ 'pages' : { $gt : ?0 } }")
    List<Book> findBooksByPagesGreaterThan(int pages);
}

In this example, @Query annotations specify MongoDB query strings to find books by author and pages greater than a specified value. Using @Query annotation, we have full control over query construction and execution.

For detailed reference on @Query annotation including mutiple examples, kindly visit a separate article on MongoDB @Query Examples With Spring Boot.

3) Using MongoTemplate

MongoTemplate is a class provided by Spring Data MongoDB that comes under the package org.springframework.data.mongodb.core. It offers a rich set of methods for performing operations on MongoDB collections within our Spring Boot application. MongoTemplate allows developers to execute arbitrary MongoDB queries using the MongoDB Java driver, providing full control over query execution and result processing.

  • MongoTemplate is a lower-level MongoDB operations template to interact with MongoDB provided by Spring Data MongoDB.
  • It gives us more control over query construction and execution.

For example, Let’s assume the same usecase as to find books by author and pages greater than a specified value:

import java.util.List;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

public class BookService {

   private final MongoTemplate mongoTemplate;

   public BookService(MongoTemplate mongoTemplate) {

      this.mongoTemplate = mongoTemplate;
   }

   public List<Book> findBooksByAuthor(String author) {
      
      Query query = new Query(Criteria.where("author").is(author));
      return mongoTemplate.find(query, Book.class);
   }

   public List<Book> findBooksByPagesGreaterThan(int pages) {
     
      Query query = new Query(Criteria.where("pages").gt(pages));
      return mongoTemplate.find(query, Book.class);
   }
}

In this example, MongoTemplate is used to construct and execute MongoDB queries to find books by author and pages greater than a specified value. While MongoTemplate offers maximum flexibility, it requires developers to write and manage raw MongoDB queries.

For detailed reference on MongoTemplate including mutiple examples, kindly visit a separate article on MongoTemplate With Spring Boot.

Comparison: MongoRepository vs. @Query annotation vs. MongoTemplate

  • MongoRepository is the easiest and most convenient way to work with MongoDB in Spring Boot. It is suitable for common CRUD operations and simple queries. It removes query implementation details and helps in making code more readable and maintainable.
  • @Query Annotation provides versatility to execute custom MongoDB queries within repository interfaces and offers a balance between convenience and control. It is suitable for situations where method naming conventions are not enough.
  • MongoTemplate offers maximum flexibility and control over MongoDB queries, but requires developers to write and manage custom MongoDB query strings. It is suitable for complex queries and scenarios which requires low-level MongoDB operations.

FAQ

What is the purpose of the @Query annotation?

The @Query annotation allows us to define custom queries directly in our repository interface. We can write MongoDB-specific queries using the MongoDB query language.

How do we create a custom query using MongoRepository? 

We can create custom queries in MongoRepository by defining methods with specific naming conventions, such as findBy<Property> or findBy<Property>And<Property>. Spring Data MongoDB translates these method names into MongoDB queries.

Can we add custom queries with MongoRepository?

Yes, we can add custom queries by defining method signatures in our repository interface. Spring Data MongoDB will automatically generate the query based on the method name.

How do we use @Query Annotation?

Annotate a method in your repository interface with @Query and provide the query string. We can also use placeholders for method parameters.

Can we use complex queries with @Query?

Yes, we can write complex queries involving conditions, projections, and sorting using @Query.

When should we use @Query annotation instead of MongoRepository methods?

We should use @Query annotation when we need to execute complex queries that cannot be expressed using the method naming conventions of MongoRepository.

Can we use @Query annotation with native MongoDB queries?

Yes, @Query annotation supports both native MongoDB queries and Spring Data MongoDB’s Query DSL.

How do we use MongoTemplate?

We can inject MongoTemplate into our service or component, and then use it to perform operations like querying, updating, and aggregating data.

When should we use MongoTemplate instead of MongoRepository or @Query annotation?

We should use MongoTemplate when we need maximum flexibility and control over MongoDB queries, such as executing complex aggregation queries or interacting with MongoDB features not supported by MongoRepository or @Query annotation.

Which one is better to use among MongoRepository, @Query annotation, and MongoTemplate?

The choice between MongoRepository, @Query annotation, and MongoTemplate depends on the specific requirements of our application, balancing ease of use with flexibility and control.

Can we use MongoTemplate for bulk operations?

Absolutely! We can perform bulk updates or inserts using methods like insertAll(), findAll(), findAllAndRemove(). These are very useful when we need to process large amounts of data efficiently.

Conclusion

Spring Data MongoDB simplifies data access in Java applications by providing a high-level abstraction layer over MongoDB. We can build robust and scalable applications easily using its features, such as POJO mapping, repository support, and Query DSL. By utilizing the power of Spring Data MongoDB, we can focus on developing an efficient application without worrying about the possible challenges during database interaction.

In this article, we have covered the basics of Spring Data MongoDB, including its key features, usage, and query examples. Additionally, we have covered a comparative study among the common ways i.e. using MongoRepository, @Query annotation, and MongoTemplate. At the last, we have also gone through the most important FAQs.

References

Spring Data MongoDB Documentation: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/
MongoDB Documentation: https://docs.mongodb.com/manual/

 

Leave a Reply


Top