Spring Boot and MongoDB Tutorial with Examples

View more Tutorials:

Websites to learn foreign languages for free:
Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter
In this lesson, I am going to show you how to  create a Spring Boot application connected to MongoDB database and learn about Spring data MongoDB.

1- Create Spring Boot project

On the Eclipse, create a Spring Boot ​​​​​​​project.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"


    <description>Spring Boot +MongoDB</description>

        <relativePath/> <!-- lookup parent from repository -->






2- Configure MongoDB

For Spring Boot to be able to connect the MongoDB database, you need to configure the properities in the applications.properties file.


In this application, I connect it to the "mydatabase" of the MongoDB. Don't worry. If the "mydatabase" doesn't exist, it will automatically be created.

3- Spring Data MongoDB

Spring Data MongoDB is a library of Spring. It helps you easily work with the MongoDB. For example, you have a Collection T and you want to create a Class with 4 functions such as querying, adding, editing, deleting on this Collection. It is very simple!

According to the rule of the Spring Data MongoDB, you just need to define an extended interface- MongoRepository<T,ID> interface, and declare methods to manipulate with the data of this collection. The Spring Data MongoDB will create a class that implements that interface for you. Of course, the name of the methods must follow a rule made by the Spring Data MongoDB.
For instance, on the database, we have Employee collection, which corresponds with the Employee class of Java. The fields of this collection will correspond with the fields of the Employee class. The ID field is primary key.

package org.o7planning.sbmongodb.document;

import java.util.Date;

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

@Document(collection = "Employee")
public class Employee {

    private Long id;

    @Indexed(unique = true)
    @Field(value = "Emp_No")
    private String empNo;

    @Field(value = "Full_Name")
    private String fullName;

    @Field(value = "Hire_Date")
    private Date hireDate;

    public Long getId() {
        return id;

    public void setId(Long id) {
        this.id = id;

    public String getEmpNo() {
        return empNo;

    public void setEmpNo(String empNo) {
        this.empNo = empNo;

    public String getFullName() {
        return fullName;

    public void setFullName(String fullName) {
        this.fullName = fullName;

    public Date getHireDate() {
        return hireDate;

    public void setHireDate(Date hireDate) {
        this.hireDate = hireDate;

    public String toString() {
        return "id:" + this.id + ", empNo: " + empNo //
                + ", fullName: " + this.fullName + ", hireDate: " + this.hireDate;
EmployeeRepository Interface extends MongoRepository<Employee, Long> interface.It has methods to manipulate with the Employee collection. The Spring Data MongoDB will automatically create a class that implements this interface at the time of running the application.

package org.o7planning.sbmongodb.repository;

import java.util.Date;
import java.util.List;

import org.o7planning.sbmongodb.document.Employee;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

// This is an Interface.
// No need Annotation here
public interface EmployeeRepository extends MongoRepository<Employee, Long> { // Long: Type of Employee ID.

    Employee findByEmpNo(String empNo);

    List<Employee> findByFullNameLike(String fullName);

    List<Employee> findByHireDateGreaterThan(Date hireDate);

    // Supports native JSON query string
    List<Employee> findCustomByFullName(String fullName);

The Spring Data MongoDB will automaticallty create methods to implement the abstract methods of Interface. Below is a list of supported keywords for data query methods: 
Keyword Sample Logical result
GreaterThan findByAgeGreaterThan(int age) {"age" : {"$gt" : age}}
LessThan findByAgeLessThan(int age) {"age" : {"$lt" : age}}
Between findByAgeBetween(int from, int to) {"age" : {"$gt" : from, "$lt" : to}}
IsNotNull, NotNull findByFirstnameNotNull() {"age" : {"$ne" : null}}
IsNull, Null findByFirstnameNull() {"age" : null}
Like findByFirstnameLike(String name) {"age" : age} ( age as regex)
(No keyword) findByFirstname(String name) {"age" : name}
Not findByFirstnameNot(String name) {"age" : {"$ne" : name}}
Near findByLocationNear(Point point) {"location" : {"$near" : [x,y]}}
Within findByLocationWithin(Circle circle) {"location" : {"$within" : {"$center" : [ [x, y], distance]}}}
Within findByLocationWithin(Box box) {"location" : {"$within" : {"$box" : [ [x1, y1], x2, y2]}}}
You can also create interfaces with custom methods. In this case, you have to write the class to implement such interface.

package org.o7planning.sbmongodb.repository;

import java.util.Date;

public interface EmployeeRepositoryCustom {

    public long getMaxEmpId();
    public long updateEmployee(String empNo, String fullName, Date hireDate);

package org.o7planning.sbmongodb.repository;

import java.util.Date;

import org.o7planning.sbmongodb.document.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.mongodb.client.result.UpdateResult;

public class EmployeeRepositoryCustomImpl implements EmployeeRepositoryCustom {

    MongoTemplate mongoTemplate;

    public long getMaxEmpId() {
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC, "id"));
        Employee maxObject = mongoTemplate.findOne(query, Employee.class);
        if (maxObject == null) {
            return 0L;
        return maxObject.getId();

    public long updateEmployee(String empNo, String fullName, Date hireDate) {
        Query query = new Query(Criteria.where("empNo").is(empNo));
        Update update = new Update();
        update.set("fullName", fullName);
        update.set("hireDate", hireDate);

        UpdateResult result = this.mongoTemplate.updateFirst(query, update, Employee.class);

        if (result != null) {
            return result.getModifiedCount();

        return 0;


4- Controller


package org.o7planning.sbmongodb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

public class SpringBootMongoDbApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootMongoDbApplication.class, args);

    public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, MongoMappingContext context) {

        MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory), context);
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));

        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter);

        return mongoTemplate;


package org.o7planning.sbmongodb.controller;

import java.util.Date;
import java.util.List;

import org.o7planning.sbmongodb.document.Employee;
import org.o7planning.sbmongodb.repository.EmployeeRepository;
import org.o7planning.sbmongodb.repository.EmployeeRepositoryCustom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

public class MainController {

    private static final String[] NAMES = { "Tom", "Jerry", "Donald" };

    private EmployeeRepositoryCustom employeeRepositoryCustom;

    private EmployeeRepository employeeRepository;

    public String home() {
        String html = "";
        html += "<ul>";
        html += " <li><a href='/testInsert'>Test Insert</a></li>";
        html += " <li><a href='/showAllEmployee'>Show All Employee</a></li>";
        html += " <li><a href='/showFullNameLikeTom'>Show All 'Tom'</a></li>";
        html += " <li><a href='/deleteAllEmployee'>Delete All Employee</a></li>";
        html += "</ul>";
        return html;

    public String testInsert() {
        Employee employee = new Employee();

        long id = this.employeeRepositoryCustom.getMaxEmpId() + 1;
        int idx = (int) (id % NAMES.length);
        String fullName = NAMES[idx] + " " + id;

        employee.setEmpNo("E" + id);
        employee.setHireDate(new Date());

        return "Inserted: " + employee;

    public String showAllEmployee() {

        List<Employee> employees = this.employeeRepository.findAll();

        String html = "";
        for (Employee emp : employees) {
            html += emp + "<br>";

        return html;

    public String showFullNameLikeTom() {

        List<Employee> employees = this.employeeRepository.findByFullNameLike("Tom");

        String html = "";
        for (Employee emp : employees) {
            html += emp + "<br>";

        return html;

    public String deleteAllEmployee() {

        return "Deleted!";


5- Run the application

View more Tutorials: