How to Seamlessly Integrate MongoDB with Spring Boot: A Step‑by‑Step Guide

This tutorial walks you through upgrading Spring Boot, introduces MongoDB basics, and provides a hands‑by‑step guide to adding the spring‑boot‑starter‑data‑mongodb dependency, defining entity and repository classes, writing unit tests, and configuring connection properties for robust backend data management.

Programmer DD
Programmer DD
Programmer DD
How to Seamlessly Integrate MongoDB with Spring Boot: A Step‑by‑Step Guide

Due to recent team adjustments, the author resumes the series on upgrading Spring Boot 1.x to 2.x, explaining version‑specific changes so readers of any version can find relevant information.

The next focus will be advanced Spring Boot topics, such as extension points.

MongoDB Overview

MongoDB is a distributed document‑oriented database that bridges the gap between key/value stores and traditional RDBMS, offering high performance, scalability, and rich features.

It stores data in a flexible BSON format similar to JSON, making it easy to handle complex types and integrate smoothly with Node.js applications.

As a NoSQL database, MongoDB provides a powerful, object‑oriented query language that supports most relational‑style queries and indexing.

However, MongoDB is not a universal replacement for relational databases; each has its own strengths depending on data types and transaction requirements.

Typical use cases include storing key‑value pairs (e.g., verification codes, sessions), large‑scale data such as logs or comments, and flexible JSON payloads for external system interactions, while high‑transaction scenarios like account transfers are better suited to relational databases.

Hands‑On Example

Step 1: Add Dependency

Include spring-boot-starter-data-mongodb in pom.xml to enable MongoDB access via Spring Data.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Step 2: Create Entity –

User
@Data
public class User {
    @Id
    private Long id;
    private String username;
    private Integer age;
}

Step 3: Define Repository –

UserRepository
public interface UserRepository extends MongoRepository<User, Long> {
    User findByUsername(String username);
}

Spring Data provides the same concise and easy‑to‑use API as other Spring Data modules.

Step 4: Write Unit Test

@SpringBootTest(classes = Chapter61Application.class)
public class ApplicationTests {
    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() throws Exception {
        userRepository.deleteAll();
        userRepository.save(new User(1L, "didi", 30));
        userRepository.save(new User(2L, "mama", 40));
        userRepository.save(new User(3L, "kaka", 50));
        Assertions.assertEquals(3, userRepository.findAll().size());
        User u = userRepository.findById(1L).get();
        userRepository.delete(u);
        Assertions.assertEquals(2, userRepository.findAll().size());
        u = userRepository.findByUsername("mama");
        userRepository.delete(u);
        Assertions.assertEquals(1, userRepository.findAll().size());
    }
}
Note: The Assertions class is used in Spring Boot 2.4 and later; earlier versions use Assert .

Step 5: Configure Connection

Add the MongoDB URI to application.properties:

spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test

Ensure the test database has a user with read/write permissions. For MongoDB 2.x, you can use the older host/port properties (not supported in 3.x):

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017

Side Note

Although MongoDB received considerable attention in the past, its adoption has slowed, with many projects now preferring Elasticsearch for better performance in large‑scale scenarios.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend Developmentunit testingSpring BootMongoDBspring-datadatabase integration
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.