Getting Started with Spring Boot and MongoDB

In this article, we’ll learn how to connect the Spring Boot application with the MongoDB database and access data from the MongoDB database. MongoDB is a cross-platform document-oriented database commonly known as a NoSQL database. MongoDB is a document database, which means it stores data in JSON-like documents.

Spring provides inbuilt interfaces and annotations that help to access and connect with MongoDB database like:

  • MongoRepository<T, ID> is an interface that provides basic CRUD methods similar to CrudRepository Interface.
  • @Document annotation helps to define the name of the document similar to the @Table annotation.

What we’ll build

On this page, we’ll create a brand new Spring Boot application and connect the application with the MongoDB database to insert and fetch the data from the database.

Technology Used

Find the list of all tools and technologies used in this application.

  1. IntelliJ IDEA
  2. JDK 8
  3. Spring Boot 2.3.3.RELEASE
  4. MongoDB 4.4.1 Database
  5. Maven 3.6

Dependencies Required

Accessing data with MongoDB, the following dependencies must be available in the application classpath.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""
        <relativePath/> <!-- lookup parent from repository -->





Project Structure

The final project structure of our application in IntelliJ IDEA IDE will look like as follows:

Getting Started with Spring Boot and MongoDB

Define a Simple Document (POJO)

Create a simple Employee class with its attributes and generates the getters and setters and parameterized constructors.
package org.websparrow.dto;


public class Employee {

    private String id;
    private String firstName;
    private String lastName;
    private Character gender;
    private int age;
    // Generate Getters and Setters...

    public Employee() {

    public Employee(String firstName, String lastName, Character gender, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.gender = gender;
        this.age = age;

    public String toString() {
        return "Employee{" +
                "id='" + id + '\'' +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", gender=" + gender +
                ", age=" + age +

By default, Spring Data MongoDB uses the class name to create the collection name in the MongoDB database. We can use the @Document(collection = "employees") annotation on the class to change the collection name.

Create Repository

In order to query with the MongoDB database, the EmployeeRepository interface will extend the MongoRepository<TID> interface which provides the basic CRUD operation methods and we can also create our Derived findBy Query Methods.
package org.websparrow.repository;

import org.springframework.stereotype.Repository;
import org.websparrow.dto.Employee;

import java.util.List;

public interface EmployeeRepository extends MongoRepository<Employee, String> {

    List<Employee> findByFirstName(String firstName);
    List<Employee> findByGender(Character gender);

Define Database Connection Strings file comes in the picture to define the MongoDB database connection strings.
#Database connection strings{db-username}{your-secret-password}

By default, Spring Data try to connect the application at localhost:27017/test if we don’t define the connection parameters.

Execute it

The final step is executing the application. To do that, create a Spring Boot runner class i.e. SpringBootMongoDBApp which implements the CommandLineRunner interface. Overrides it’s run() method and call the required methods of the EmployeeRepository interface.
package org.websparrow;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.websparrow.dto.Employee;
import org.websparrow.repository.EmployeeRepository;

import java.util.List;

public class SpringBootMongoDBApp implements CommandLineRunner {

    public static void main(String[] args) {, args);

    private EmployeeRepository employeeRepository;

    public void run(String... args) throws Exception {

        // Save the employees Employee("Atul", "Rai", 'M', 28)); Employee("Pallavi", "Tripathi", 'F', 25)); Employee("Manish", "Fartiyal", 'M', 30)); Employee("Lucifer", "**", 'F', 33));

        // Fetch the all employees
        List<Employee> employees = employeeRepository.findAll();
        System.out.println("============ List of all employees ============");

        // Fetch the all employees by first name
        List<Employee> employeesByFirstName = employeeRepository.findByFirstName("Manish");
        System.out.println("============ List of all employees by first name ============");

        // Fetch the all employees by gender
        List<Employee> employeesByGender = employeeRepository.findByGender('F');
        System.out.println("============ List of all employees by gender ============");



After the successful execution, you will find the below output on your IDE console log.

console log
============ List of all employees ============
	Employee{id='5f66fcebf00ba2568d60b7e0', firstName='Atul', lastName='Rai', gender=M, age=28}, Employee{id='5f66fcebf00ba2568d60b7e1', firstName='Pallavi', lastName='Tripathi', gender=F, age=25}, Employee{id='5f66fcebf00ba2568d60b7e2', firstName='Manish', lastName='Fartiyal', gender=M, age=30}, Employee{id='5f66fcebf00ba2568d60b7e3', firstName='Lucifer', lastName='**', gender=F, age=33}
============ List of all employees by first name ============
	Employee{id='5f66fcebf00ba2568d60b7e2', firstName='Manish', lastName='Fartiyal', gender=M, age=30}
============ List of all employees by gender ============
	Employee{id='5f66fcebf00ba2568d60b7e1', firstName='Pallavi', lastName='Tripathi', gender=F, age=25}, Employee{id='5f66fcebf00ba2568d60b7e3', firstName='Lucifer', lastName='**', gender=F, age=33}

To verify it, you can also check the MongoDB database.

Spring Boot and MongoDB- Compass Data viewer


  1. Spring Data MongoDB – Reference Documentation
  2. MongoDB Website
  3. MongoDB Docs

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.