TutorialDatabase
MongoDB with Spring Data: A Practical Guide
Skip the boilerplate. Learn how Spring Data MongoDB turns your domain classes into a fully-functional persistence layer in minutes.
Chaturmind Team
MongoDB with Spring Data: A Practical Guide
Spring Data MongoDB makes it easy to persist Java objects to MongoDB without writing a single query.
Add the dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Define your document
@Document("articles")
public class Article {
@Id
private String id;
@Indexed(unique = true)
private String slug;
private String title;
private String content;
@CreatedDate
private Instant createdAt;
@LastModifiedDate
private Instant updatedAt;
}
Create a repository
public interface ArticleRepository extends MongoRepository<Article, String> {
Optional<Article> findBySlug(String slug);
List<Article> findByTitleContainingIgnoreCase(String keyword);
Page<Article> findByStatus(PublishStatus status, Pageable pageable);
}
Spring Data generates the query from the method name — no JPQL, no Mongo query shell needed.
Compound indexes
@Document("articles")
@CompoundIndexes({
@CompoundIndex(def = "{'status': 1, 'publishedAt': -1}"),
@CompoundIndex(def = "{'category': 1, 'status': 1}")
})
public class Article { ... }
Custom aggregation
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(Criteria.where("status").is("PUBLISHED")),
Aggregation.group("category").count().as("total"),
Aggregation.sort(Sort.by(Sort.Direction.DESC, "total"))
);
List<CategoryCount> results = mongoTemplate.aggregate(agg, "articles", CategoryCount.class).getMappedResults();
Related Posts
✍️
FeaturedBlogSpring Boot
What's New in Spring Boot 3
Spring Boot 3 ships with Java 17 baseline, native AOT compilation, and major security upgrades. Here's everything you need to know before migrating.
Chaturmind TeamJan 20, 2025
✍️
BlogDatabase
SQL vs NoSQL: How to Choose the Right Database
Choosing between SQL and NoSQL is one of the most common system design questions. Here's a principled framework — not just "it depends".
Chaturmind TeamMar 15, 2025