Integrating Spring Boot with MongoDB: A Step‑by‑Step Guide

This article explains how to integrate MongoDB into a Spring Boot application, covering suitable use cases, environment setup, core dependencies, configuration, entity mapping, CRUD operations via MongoRepository and MongoTemplate, indexing, performance considerations, and a concise comparison with MySQL.

Java Tech Workshop
Java Tech Workshop
Java Tech Workshop
Integrating Spring Boot with MongoDB: A Step‑by‑Step Guide

1. MongoDB Use Cases

Articles, blogs, comments, logs with variable fields

User profiles, behavior data, event tracking

Configuration centers, dynamic forms, product details

High‑volume writes with low transaction requirements

Frequent schema changes without altering table structures

2. Environment Preparation

Install and start MongoDB (local or cloud)

Spring Boot 2.x / 3.x

MongoDB client tools such as Navicat or MongoDB Compass

3. Core Dependency

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

<!-- Lombok -->
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <optional>true</optional>
</dependency>

4. application.yml Configuration

spring:
  data:
    mongodb:
      # No‑password connection
      uri: mongodb://localhost:27017/mongo_demo
      # With authentication (example)
      # uri: mongodb://root:123456@localhost:27017/mongo_demo?authSource=admin
mongo_demo

is the database name; it will be created automatically if absent.

No need to manually create collections; they are generated on first insert.

5. Common MongoDB Annotations

@Document

: Marks a class as a MongoDB document and maps it to a collection. @Id: Primary key, defaults to generating _id. @Field("field_name"): Specifies the field name in the database. @Transient: Field is not persisted. @Indexed: Creates an index to improve query speed. @CompoundIndex: Defines a compound index.

6. Entity Class Example

package com.demo.entity;

import lombok.Data;
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;
import java.time.LocalDateTime;
import java.util.List;

@Data
@Document(collection = "article") // collection name
public class Article {
    @Id
    private String id;

    @Indexed // index on title
    private String title;

    private String content;

    @Field("author_name")
    private String authorName;

    private Integer viewCount;
    private List<String> tags;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

7. Two Ways to Operate MongoDB

Spring Boot offers two approaches:

MongoRepository : Simple CRUD similar to JPA.

MongoTemplate : Flexible for complex queries, aggregations, and updates; more commonly used in production.

7.1 MongoRepository Quick CRUD

1. Repository Interface

package com.demo.repository;

import com.demo.entity.Article;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public interface ArticleRepository extends MongoRepository<Article, String> {
    // Find by author name
    List<Article> findByAuthorName(String authorName);
    // Fuzzy search by title
    List<Article> findByTitleLike(String title);
}

2. Service with Basic CRUD

@Service
@RequiredArgsConstructor
public class ArticleService {
    private final ArticleRepository repository;

    // Save or update
    public Article save(Article article) {
        article.setCreateTime(LocalDateTime.now());
        return repository.save(article);
    }

    // Find by ID
    public Article findById(String id) {
        return repository.findById(id).orElse(null);
    }

    // Find all
    public List<Article> findAll() {
        return repository.findAll();
    }

    // Delete by ID
    public void deleteById(String id) {
        repository.deleteById(id);
    }

    // Find by author name
    public List<Article> findByAuthor(String authorName) {
        return repository.findByAuthorName(authorName);
    }
}

7.2 MongoTemplate Complex Queries

Enterprise projects usually prefer MongoTemplate for its flexibility and power.

1. General Conditional Query

@Autowired
private MongoTemplate mongoTemplate;

// Build query
Query query = new Query();
// Exact match
query.addCriteria(Criteria.where("authorName").is("张三"));
// Greater than
query.addCriteria(Criteria.where("viewCount").gt(100));
// Regex (contains "Java")
query.addCriteria(Criteria.where("title").regex("Java"));
// AND condition
query.addCriteria(Criteria.where("authorName").is("张三").and("viewCount").gt(100));
// OR condition
query.addCriteria(new Criteria().orOperator(
        Criteria.where("authorName").is("张三"),
        Criteria.where("viewCount").gt(1000)
));

List<Article> list = mongoTemplate.find(query, Article.class);

2. Pagination Query

// Page index starts from 0
Pageable pageable = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "createTime"));
Query pageQuery = new Query().with(pageable);
List<Article> pageList = mongoTemplate.find(pageQuery, Article.class);
long total = mongoTemplate.count(pageQuery, Article.class);

3. Field Update

// Increment viewCount by 1
Query query = Query.query(Criteria.where("_id").is(id));
Update update = new Update().inc("viewCount", 1);
mongoTemplate.updateFirst(query, update, Article.class);

4. Batch Update

mongoTemplate.updateMulti(query, update, Article.class);

5. Aggregation (Statistics, Grouping)

// Group by authorName and count articles
Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.group("authorName").count().as("count"),
        Aggregation.sort(Sort.by(Sort.Direction.DESC, "count"))
);
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, "article", Map.class);
List<Map> mapList = results.getMappedResults();

8. MongoDB Indexes

Adding indexes to frequently queried fields greatly improves performance.

// Single‑field index
@Indexed

// Unique index
@Indexed(unique = true)

// Compound index
@CompoundIndex(def = "{'authorName':1, 'createTime':-1}")

After creation, view them in MongoDB with:

db.article.getIndexes()

9. MongoDB vs MySQL Simple Comparison

MySQL: Fixed table schema, strong transactions, suitable for strong consistency.

MongoDB: Flexible schema, no table constraints, fast queries, ideal for massive semi‑structured data.

10. Precautions

No default transaction guarantees atomicity ; high concurrency requires locking or explicit transactions.

Do not create excessive indexes; they degrade write performance.

Documents larger than 16 MB should not be stored directly; store file service URLs instead.

Regex queries do not use indexes; prefer prefix matching.

Deep pagination suffers performance loss; cursor‑based pagination is recommended.

11. Summary

Integrating MongoDB with Spring Boot is straightforward: add the starter dependency, configure the connection, define entity classes, and use either MongoRepository for simple CRUD or MongoTemplate for advanced operations. The flexible schema and rapid development make it well‑suited for articles, comments, logs, and user‑behavior data, covering most business 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.

Javaspring-bootMongoDBNoSQLSpring DataMongoRepositoryMongoTemplate
Java Tech Workshop
Written by

Java Tech Workshop

Focused on Java backend technologies, sharing fundamentals, multithreading, JVM, the Spring ecosystem, microservices, distributed systems, high concurrency, source‑code analysis, and practical experience. Continuously delivers high‑quality original content, interview guides, and learning roadmaps to help Java developers progress from beginner to advanced, enhancing technical skills and core competitiveness.

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.