Spring Boot – MongoRepository with Example
Last Updated :
03 Jan, 2022
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 setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:
- It allows avoiding heavy configuration of XML which is present in spring
- It provides easy maintenance and creation of REST endpoints
- It includes embedded Tomcat-server
- Deployment is very easy, war and jar files can be easily deployed in the tomcat server
For more information please refer to this article: Introduction to Spring Boot. In this article, we are going to discuss how to use MongoRepository to manage data in a Spring Boot application.
MongoRepository
MongoRepository is an interface provided by Spring Data in the package org.springframework.data.mongodb.repository. MongoRepository extends the PagingAndSortingRepository and QueryByExampleExecutor interfaces that further extend the CrudRepository interface. MongoRepository provides all the necessary methods which help to create a CRUD application and it also supports the custom derived query methods.
Syntax:
public interface MongoRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>
Where:
- T: Domain type that repository manages (Generally the Entity/Model class name)
- ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)
Illustration:
public interface BookRepo extends MongoRepository<Book, Integer> {}
Methods
Some of the most important methods that are available inside the JpaRepository are given below
Method 1: saveAll(): It saves all given entities.
Syntax:
<S extends T> List<S> saveAll(Iterable<S> entities)
Parameters: Entities, must not be null nor must they contain null.
Return Type: The saved entities; will never be null. The returned Iterable will have the same size as the Iterable passed as an argument.
Exception Thrown: IllegalArgumentException in case the given entities or one of its entities is null.
Method 2: insert(): Inserts the given entity. Assumes the instance to be new to be able to apply insertion optimizations. Use the returned instance for further operations as the save operation might have changed the entity instance completely.
Syntax:
<S extends T> S insert(S entity)
Parameters: entity – must not be null
Return Type: the saved entity
Method 3. findAll(): Returns all instances of the type.
Syntax:
Iterable<T> findAll()
Return Type: All entities
Implementation:
We will be making a Spring Boot application that manages a Book entity with MongoRepository. The data is saved in the MongoDB database. We use a RESTful controller.
Step 1: Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project.
Step 2: Add the following dependency
- Spring Web
- MongoDB
- Lombok
- DevTools
Below is the complete code for the pom.xml file.
XML
<? xml version = "1.0" encoding = "UTF-8" ?>
< modelVersion >4.0.0</ modelVersion >
< parent >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-starter-parent</ artifactId >
< version >2.6.0</ version >
< relativePath />
</ parent >
< groupId >com.globallogic</ groupId >
< artifactId >spring-mongodb</ artifactId >
< version >0.0.1-SNAPSHOT</ version >
< name >spring-mongodb</ name >
< description >Demo project for Spring Boot</ description >
< properties >
< java.version >11</ java.version >
</ properties >
< 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 >
< dependency >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-devtools</ artifactId >
< scope >runtime</ scope >
< optional >true</ optional >
</ dependency >
< dependency >
< groupId >org.projectlombok</ groupId >
< artifactId >lombok</ artifactId >
< optional >true</ optional >
</ dependency >
< dependency >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-starter-test</ artifactId >
< scope >test</ scope >
</ dependency >
</ dependencies >
< build >
< plugins >
< plugin >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-maven-plugin</ artifactId >
< configuration >
< excludes >
< exclude >
< groupId >org.projectlombok</ groupId >
< artifactId >lombok</ artifactId >
</ exclude >
</ excludes >
</ configuration >
</ plugin >
</ plugins >
</ build >
</ project >
|
Step 3: Create 3 packages and create some classes and interfaces inside these packages as seen in the below image
- model
- repository
- controller

Note:
- Green Rounded Icon ‘I’ Buttons are Interface
- Blue Rounded Icon ‘C’ Buttons are Classes
Step 4: Inside the entity package
Creating a simple POJO class inside the Book.java file.
Java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document (collection = "Book" )
public class Book {
@Id
private int id;
private String bookName;
private String authorName;
}
|
Step 5: Inside the repository package
Create a simple interface and name the interface as BookRepo. This interface is going to extend the MongoRepository as we have discussed above.
Java
import com.globallogic.spring.mongodb.model.Book;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface BookRepo
extends MongoRepository<Book, Integer> {
}
|
Step 6: Inside the controller package
Inside the package create one class named as BookController.
Java
import com.globallogic.spring.mongodb.model.Book;
import com.globallogic.spring.mongodb.repository.BookRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class BookController {
@Autowired
private BookRepo repo;
@PostMapping ( "/addBook" )
public String saveBook( @RequestBody Book book){
repo.save(book);
return "Added Successfully" ;
}
@GetMapping ( "/findAllBooks" )
public List<Book> getBooks() {
return repo.findAll();
}
@DeleteMapping ( "/delete/{id}" )
public String deleteBook( @PathVariable int id){
repo.deleteById(id);
return "Deleted Successfully" ;
}
}
|
Step 7: Below is the code for the application.properties file
server.port = 8989
# MongoDB Configuration
server.port:8989
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=BookStore
Step 8: Inside the MongoDB Compass
Go to your MongoDB Compass and create a Database named BookStore and inside the database create a collection named Book as seen in the below image

Now run your application and let’s test the endpoints in Postman and also refer to our MongoDB Compass.
Testing the Endpoint in Postman
Endpoint 1: POST – http://localhost:8989/addBook

Endpoint 2: GET – http://localhost:8989/findAllBooks

Endpoint 3: DELETE – http://localhost:8989/delete/1329

Finally, MongoDB Compass is as depicted in the below image as shown below as follows:

Similar Reads
Spring Boot - JDBC
Spring Boot JDBC is used to connect the Spring Boot application with JDBC by providing libraries and starter dependencies. Spring Boot JDBC has a level of control over the SQL queries that are being written. Spring Boot JDBC has simplified the work of Spring JDBC by automating the work and steps by
8 min read
Spring Boot - AOP After Throwing Advice
Spring is widely used for creating scalable applications. For web applications Spring provides. Spring MVC is a widely used module of spring that is used to create scalable web applications. While Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as
6 min read
Spring Boot - AOP After Returning Advice
Prerequisite: Aspect Oriented Programming and AOP in Spring Framework Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Asp
5 min read
Multi-Module Project With Spring Boot
Multi-Module project with Spring Boot refers to a project structure where multiple modules or subprojects are organized under a single parent project. Each module can represent a distinct component, functionality, or layer of the application, allowing for better organization, maintainability, and co
6 min read
Spring Boot - AOP After Advice
Prerequisite: Aspect Oriented Programming and AOP in Spring Framework Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Asp
5 min read
Spring Boot - AOP Before Advice
Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting concerns such as transa
4 min read
Spring Boot - DevTools
Spring Boot provides DevTools, a module designed to ease your development process, it improves the experience of developing applications resulting in optimizing the developer's productivity for building exceptional software. It aims to reduce development time, by intelligently detecting code changes
5 min read
Spring Boot - Dependency Management
Spring Boot framework is the most popular web development framework. No doubt, it provides an abundance of essential features and a convenient way to handle those features. At the heart of Spring Boot is the 'Dependency Management' feature. Importance of Dependency ManagementCentralized Dependency M
6 min read
Spring Boot - Caching
Spring Boot is a project that is built on top of the Spring Framework that provides an easier and faster way to set up, configure, and run both simple and web-based applications. It is one of the popular frameworks among developers these days because of its rapid production-ready environment which e
6 min read
Spring Boot - Starter Web
Today most of the applications demand Model-View-Controller (MVC) architecture to meet the various needs like handling user data, making application efficient, to provide dynamic nature to applications. It was basically used for building desktop graphical user interfaces (GUIs), but now is becoming
6 min read