Getting Started with Spring Boot and MongoDB: Step‑by‑Step Guide and Sample Code

This article introduces MongoDB fundamentals, walks through Windows installation, shows how to integrate Spring Boot with MongoDB via Maven, configures connection settings, demonstrates both MongoRepository and MongoTemplate usage with full code examples, and compares MongoDB to Redis for typical use cases.

The Dominant Programmer
The Dominant Programmer
The Dominant Programmer
Getting Started with Spring Boot and MongoDB: Step‑by‑Step Guide and Sample Code

MongoDB is an open‑source, distributed, document‑oriented NoSQL database that stores data as BSON (binary JSON). It is schemaless, supports horizontal scaling and sharding, and is suited for large‑scale, high‑concurrency scenarios such as logs, user profiles, IoT, and content management, while being less appropriate for strong transactional workloads.

Windows Installation (Minimal)

Download the community edition from the official site, choose the MSI package, and follow the default wizard. The service starts automatically on port 27017 without a password. After installation, the database is reachable at localhost:27017 and a test database (e.g., testdb) can be created on demand.

Spring Boot Integration Steps

1. Add the Spring Boot MongoDB starter dependency:

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

2. Configure the connection in application.yml:

spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      database: testdb  # created automatically if absent
      # username: root
      # password: 123456
      # authentication-database: admin

3. Define an entity class that maps to a collection:

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.LocalDateTime;
import java.util.List;

@Data
@Document(collection = "user")
public class User {
    @Id
    private String id;
    private String name;
    private Integer age;
    private String email;
    private List<String> hobbies;
    private LocalDateTime createTime;
}

Two Access Methods

Method 1 – MongoRepository (simple CRUD, JPA‑like)

Define a repository interface:

import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;

public interface UserRepository extends MongoRepository<User, String> {
    List<User> findByName(String name);
    List<User> findByAgeGreaterThan(Integer age);
}

Implement a REST controller that uses the repository for create, read, update, and delete operations.

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserRepository userRepository;

    @PostMapping
    public User save(@RequestBody User user) {
        user.setCreateTime(LocalDateTime.now());
        return userRepository.save(user);
    }

    @GetMapping
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @GetMapping("/{id}")
    public User findById(@PathVariable String id) {
        return userRepository.findById(id).orElse(null);
    }

    @GetMapping("/name/{name}")
    public List<User> findByName(@PathVariable String name) {
        return userRepository.findByName(name);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable String id) {
        userRepository.deleteById(id);
    }
}

Method 2 – MongoTemplate (flexible, enterprise‑grade)

Supports complex queries, pagination, sorting, aggregation, and indexing.

import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.*;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/user/template")
@RequiredArgsConstructor
public class UserTemplateController {
    private final MongoTemplate mongoTemplate;

    /** Conditional pagination: age >= given value, sorted by createTime descending */
    @GetMapping("/page")
    public Page<User> page(@RequestParam(defaultValue = "0") Integer age,
                          @RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer size) {
        PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "createTime"));
        Criteria criteria = Criteria.where("age").gte(age);
        Query query = Query.query(criteria).with(pageRequest);
        List<User> list = mongoTemplate.find(query, User.class);
        long total = mongoTemplate.count(query, User.class);
        return new PageImpl<>(list, pageRequest, total);
    }
}

Testing the API

After starting the application, the following endpoints are available:

POST /user – create or update a user

GET /user – retrieve all users

GET /user/template/page?age=18&page=1&size=10 – conditional pagination

The database automatically creates the testdb database and the user collection; no manual schema definition is required.

Common MongoDB Knowledge for Developers

_id

is a string primary key generated automatically.

Collections are created on first insert; no explicit table creation.

Nested objects and arrays are stored directly, ideal for frequently changing schemas.

Multi‑document transactions are supported from version 4.0 onward (replica set).

Indexes can be defined with annotations such as @CompoundIndex.

Bulk inserts achieve very high throughput.

MongoDB vs. Redis Comparison

Both are popular data stores but serve different purposes:

Redis – in‑memory, ultra‑fast cache or middleware; suitable for hot data, caching, distributed locks, rate limiting, simple key‑value access.

MongoDB – disk‑based document database; excels at flexible schemas, massive storage, complex queries, aggregation, and horizontal scaling.

Redis offers limited query capabilities (mostly key lookup), whereas MongoDB supports full query language, regex, pagination, sorting, and joins (via $lookup).

Cost: Redis memory is expensive, making it ideal for hot data; MongoDB uses cheap disk storage, handling terabytes of data cost‑effectively.

Typical MongoDB scenarios include log storage, user behavior tracking, IoT telemetry, content platforms, configuration centers, and order snapshots.

Overall, MongoDB is the preferred choice for applications that require flexible document structures, large‑scale persistence, and rich query capabilities, while Redis remains the go‑to solution for high‑performance caching and transient data.

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.

BackendJavaMongoDBspring-bootmongorepositorymongotemplatespring-data-mongodb
The Dominant Programmer
Written by

The Dominant Programmer

Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi

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.