Open In App

Spring Boot – MongoRepository with Example

Last Updated : 03 Jan, 2022
Like Article

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 is an interface provided by Spring Data in the package 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.


public interface MongoRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>


  • 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)


public interface BookRepo extends MongoRepository<Book, Integer> {}


Some of the most important methods that are available inside the JpaRepository are given below

Method 1: saveAll(): It saves all given entities.


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


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


Iterable<T> findAll()

Return Type: All entities


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 version="1.0" encoding="UTF-8"?>
        <relativePath/> <!-- lookup parent from repository -->
    <description>Demo project for Spring Boot</description>

Step 3: Create 3 packages and create some classes and interfaces inside these packages as seen in the below image

  • model
  • repository
  • controller


  • 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 file.


// Java Program to Illustrate Book File
// Importing required classes
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
// Annotations
@Document(collection = "Book")
// Class
public class Book {
    // Attributes
    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 Program to Illustrate BookRepo File
import com.globallogic.spring.mongodb.model.Book;
public interface BookRepo
    extends MongoRepository<Book, Integer> {

Step 6: Inside the controller package

Inside the package create one class named as BookController.


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;
// Annotation 
// Class 
public class BookController {
    private BookRepo repo;
    public String saveBook(@RequestBody Book book){;
        return "Added Successfully";
    public List<Book> getBooks() {
        return repo.findAll();
    public String deleteBook(@PathVariable int id){
        return "Deleted Successfully";

Step 7: Below is the code for the file

server.port = 8989

# MongoDB Configuration

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:

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads