Spring Boot – MongoRepository with Example

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 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> {}
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"?>  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">        <modelVersion>4.0.0</modelVersion>        <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.6.0</version>        <relativePath/> <!-- lookup parent from repository -->    </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
// Java Program to Illustrate Book File  // Importing required classesimport lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document;  // Annotations@Data@NoArgsConstructor@AllArgsConstructor@Document(collection = "Book")  // Classpublic class Book {      // Attributes    @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
// java Program to Illustrate BookRepo File  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;  // Annotation @RestController  // Class 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.
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:
Java-Spring-Boot
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java