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
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
ποΈDatabase
TutorialDatabase
Database Indexing Explained: B-Trees, Composite Indexes and When Indexes Hurt
How B-tree indexes make queries fast, why column order matters in composite indexes, covering indexes, reading EXPLAIN, and the cases where adding an index makes things worse.
Chaturmind TeamSep 26, 2026
ποΈDatabase
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 TeamSep 21, 2026