1. Overview

In this article, We will learn how to develop Spring boot Rest Service with MongoDB. MongoDB is a popular NoSQL database and widely used database for newly started applications. In this example, We have used Spring Data to perform the operations with the MongoDB database.

We have explained here CRUD (Create, Read, Update and Delete) operations with JSON Rest Service and used MongoDB database.

NOTE: Make sure that MongoDB server is running, By default it will run on 27017 port.

2.  Spring boot Rest Service with MongoDB Example

Spring boot Rest Service with MongoDB Example

Spring boot Rest Service with MongoDB Example

2.1 pom.xml

  • spring-boot-starter-data-mongodb for MongoDB
  • spring-boot-starter-web for Spring web and Rest Service
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <description>Spring boot Rest Service with MongoDB Example</description>
    <!-- Inherit defaults from Spring Boot -->
    <!-- Package as an executable jar -->

2.2 application.properties

  • spring.data.mongodb.host indicates MongoDB host or IP
  • spring.data.mongodb.port indicates MongoDB port

2.3 SpringBootConfig

  • @EnableMongoRepositories : It will enable MongoDB repository and we have provided based package here so it will be considered as a repository based package.
  • @SpringBootApplication: Indicate as Spring boot application
package com.javadeveloperzone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
 * Created by Java Developer Zone on 19-07-2017.
// Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
public class SpringBootConfig {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);            // it wil start application

2.4 EmployeeController

Here we have created RestController which will accept incoming HTTP request,

  • @RequestMapping(value = "save",method = RequestMethod.POST) for POST method, It will accept form parameters and save data to MongoDB database. We can directly use @GetMapping like @GetMapping(value = "save")
  • @RequestMapping(value = "list",method = RequestMethod.GET) to list all the Employee
  • @RequestMapping(value = "delete", method = RequestMethod.DELETE) to delete particular Employee
package com.javadeveloperzone.controller;
import com.javadeveloperzone.model.Employee;
import com.javadeveloperzone.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 * Created by JavaDeveloperZone on 19-07-2017.
@RestController     // for rest response
public class EmployeeController {
    private EmployeeService employeeService;
    // to add new employee
    @RequestMapping(value = "save",method = RequestMethod.POST)     // or user @GetMapping
    public Employee save(Employee employee){
        return employeeService.save(employee);
    // to update employee
    @RequestMapping(value = "update",method = RequestMethod.POST)     // or user @GetMapping
    public Employee update(Employee employee){
        return employeeService.update(employee);
    // list of all employee
    @RequestMapping(value = "list",method = RequestMethod.GET)   // or use @GetMapping
    public java.util.List<Employee> listEmployee() {
        return employeeService.findAll();
    // delete specific employee using employee id
    @RequestMapping(value = "delete", method = RequestMethod.DELETE)        // or use @DeleteMapping
    public void delete(@RequestParam("id")String id){

2.5 EmployeeService

  • It normal interface which contains CRUD methods.
package com.javadeveloperzone.service;
import com.javadeveloperzone.model.Employee;
import java.util.List;
 * Created by JavaDeveloperZone on 04-04-2018.
public interface EmployeeService {
    List<Employee> findAll();
    Employee save(Employee employee);
    void delete(String employeeId);
    Employee update(Employee employee);

2.6 EmployeeServiceImpl

  • Service Implementation where actually business logic has been written. @Service indicate service layer.
  • We have Autowire EmployeeRepository using that we can communicate with MongoDB database.
package com.javadeveloperzone.service;
import com.javadeveloperzone.repository.EmployeeRepository;
import com.javadeveloperzone.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
 * Created by Java Developer Zone on 04-04-2018.
public class EmployeeServiceImpl implements EmployeeService {
    private EmployeeRepository employeeRepository;
    public List<Employee> findAll() {
        return employeeRepository.findAll();

    public void delete(String employeeId) {
    public Employee save(Employee employee) {
        return employeeRepository.save(employee);
    public Employee update(Employee employee) {
        return employeeRepository.save(employee);

2.7 EmployeeRepository

  • Here, @Repository indicate repository which will communicate with MongoDB database and extands MongoRepository interface which contains basic methods to fetch data from MongoDB
  • Using @Query we can write a custom query which is supported by MongoDB

Here we just define method name, Spring data will automcatilly create query using method name. Here is more details for the same.

package com.javadeveloperzone.repository;
import com.javadeveloperzone.model.Employee;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;

 * Created by Java Developer Zone on 03-08-2017.
public interface EmployeeRepository extends MongoRepository<Employee,String> {
    List<Employee> findAll();           // find all Employee
    @Query(value = "{ 'employeeName' : ?0 }")
    List<Employee> findByEmployeeName(String name);       // find employee by name
    Employee findByEmployeeId(String id);           // find
    void delete(String s);              // delete by ID

2.8 Employee

  • @Document indicates the MongoDB document.
  • @Id indicate the primary key, It will not allow duplicate value. When the data type is String at that time it will automatically generate random Id.
package com.javadeveloperzone.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
 * Created by Java Developer Zone on 03-08-2017.
@Document(collection = "Employee")
public class Employee {
    @Id                                                     // primary key
    private String employeeId;
    private String employeeName;
    private String employeeRole;
    public String getEmployeeId() {
        return employeeId;
    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    public String getEmployeeRole() {
        return employeeRole;
    public void setEmployeeRole(String employeeRole) {
        this.employeeRole = employeeRole;
    public String getEmployeeName() {
        return employeeName;
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;

2.9 Output

Let’s run and check spring boot application and perform different operations:

1. Spring boot MongoDB – Save Operation

Spring boot MongoDB - Save Operation

Spring boot MongoDB – Save Operation

2. Spring boot MongoDB – List Operation

Spring boot MongoDB - List Operation

Spring boot MongoDB – List Operation

3. Spring boot MongoDB – Delete operation

Spring boot MongoDB - Delete Operation

Spring boot MongoDB – Delete Operation

3. Conclusion

We have learned about the way to develop JSON Rest Service with MongoDB database and also learned insert, update and delete operations with MongoDB in the content of Spring boot application.

4. References

5. Source Code

spring-boot-jpa-mongodb-rest-example (44 KB)

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *