MongoDB with Spring Boot
MongoDB is a document database that stores data as flexible, JSON-like documents instead of rows in tables. Spring Boot integrates with it through Spring Data MongoDB, giving you the same repository abstractions you already know from JPA, plus a powerful MongoTemplate for fine-grained control.
What is a document database?
A relational database splits data across normalized tables joined by foreign keys. MongoDB instead stores related data together in a single document — a BSON (binary JSON) structure that can contain nested objects and arrays. Documents live in collections, the rough equivalent of tables, but with no fixed schema.
{
"_id": "65f1c2a8e4b0a1d2c3e4f567",
"title": "Spring Boot in Action",
"price": 39.99,
"tags": ["spring", "java", "backend"],
"author": {
"name": "Jane Doe",
"country": "US"
}
}
Notice the embedded author object and the tags array — there is no join. The whole aggregate is read and written in one operation.
When to use MongoDB vs relational
| Choose MongoDB when… | Choose a relational DB when… |
|---|---|
| Your data is naturally hierarchical/nested | You need multi-row ACID transactions everywhere |
| The schema evolves rapidly | The schema is stable and well-known |
| You read aggregates as a whole (one entity per request) | You query across many entities with complex joins |
| You need horizontal scaling / sharding | Strong relational integrity is the priority |
| Storing variable, semi-structured data | Reporting with ad-hoc SQL is common |
MongoDB is not “better” or “worse” than SQL — it optimizes for different access patterns. For a SQL-based comparison see Spring Data JPA.
Note: MongoDB has supported multi-document ACID transactions since 4.0, but the data model still favors keeping data that changes together inside one document.
Spring Data MongoDB overview
Spring Data MongoDB provides two complementary programming models:
MongoRepository<T, ID>— a declarative repository interface. You extend it and get CRUD plus derived query methods, exactly likeJpaRepository. See MongoRepository CRUD.MongoTemplate— a lower-level helper forQuery/Criteria, atomic updates, and aggregation pipelines. See MongoTemplate.
Your domain classes are mapped with @Document and @Id, much like JPA’s @Entity. See @Document Mapping.
The starter
Add a single starter to a Spring Boot 3.5 project. It pulls in Spring Data MongoDB and the synchronous MongoDB Java driver.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Gradle:
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
With the starter on the classpath, Spring Boot auto-configures a MongoClient, a MongoTemplate, and your repositories. Point it at a running MongoDB and you are ready to persist documents.
spring.data.mongodb.uri=mongodb://localhost:27017/shopdb
Tip: For reactive, non-blocking access use
spring-boot-starter-data-mongodb-reactiveinstead, which providesReactiveMongoRepositoryandReactiveMongoTemplate. The blocking starter shown here covers the vast majority of REST applications.
A first document and repository
A minimal mapped record plus a repository is all you need to read and write documents.
@Document(collection = "products")
public record Product(@Id String id, String name, BigDecimal price) { }
public interface ProductRepository extends MongoRepository<Product, String> {
List<Product> findByNameContainingIgnoreCase(String fragment);
}
Note that the ID type is typically String because MongoDB’s _id is an ObjectId that maps cleanly to a String.
In This Section
- MongoDB Setup — connection config, Docker, and MongoDB Atlas.
- @Document Mapping —
@Document,@Id,@Field,@Indexed, and references. - MongoRepository CRUD — declarative CRUD and derived queries.
- MongoTemplate — fine-grained
Query/Criteriaand atomic updates. - Queries & @Query — derived queries, JSON
@Query, projections, sorting. - Aggregation Framework — building pipelines with Spring Data.
- Embedded vs Referenced — modeling relationships and tradeoffs.