MongoTemplate is the central class of Spring Data MongoDB for talking to MongoDB from Java. It wraps the MongoDB driver, maps documents to your domain classes, translates driver exceptions into Spring's DataAccessException hierarchy, and exposes a fluent API for CRUD operations, queries, updates, aggregations, indexes and transactions. Spring Boot auto-configures it for you when spring-boot-starter-data-mongodb is on the classpath.
Spring Data repositories are built on top of MongoTemplate, so you usually start with a repository and drop down to the template when a query, update or pipeline is too specific for a derived method name.
MongoTemplate implements the MongoOperations interface. Code that depends on MongoOperations is easier to test and mock than code that depends on the concrete class. The template gives you four things:
@Document, @Id, @Field and @Indexed.DuplicateKeyException and other DataAccessException subclasses.Query, Criteria, Update and Aggregation.@Transactional (with a replica set and a MongoTransactionManager).Add the starter and point Spring Boot at your database. No bean definition is required.
Then map a document class and inject the template through the constructor:
Constructor injection is preferred over field @Autowired because the dependency is explicit and the class is easy to unit test.
The basic methods map directly to what you expect from a data access class.
Key differences to remember:
| Method | Behaviour |
|---|---|
insert | Always creates a new document and fails on a duplicate _id. |
save | Inserts when the id is new, otherwise replaces the whole document. |
updateFirst / updateMulti | Applies partial updates ($set, $inc, $push) to one or all matching documents. |
upsert | Updates a match or inserts a new document when none exists. |
findAndModify | Atomically updates a document and returns it (before or after the change). |
Prefer Update operators over save for concurrent code. save overwrites the whole document and can erase a concurrent change, while $set and $inc touch only the fields you name.
Query holds the filter, sort, paging and projection. Criteria builds the filter.
The first part filters adults in Pune, sorts them by age and returns the first page of 20. The fields() call is a projection, so MongoDB returns only name and age (plus _id). The count query removes paging so it counts every match, not only the page.
For simpler, readable code, the fluent API reads naturally:
When you need grouping, joins or computed fields, use Aggregation. The pipeline runs inside MongoDB, so you avoid loading large result sets into the JVM.
The pipeline filters adults, groups them by city, renames the group key to city and sorts by the count. getMappedResults() returns the typed list.
@Indexed and @CompoundIndex on the entity are created automatically only when you enable it (spring.data.mongodb.auto-index-creation=true), which is off by default in Spring Boot. For production, create indexes through migrations or mongoTemplate.indexOps(Person.class).MongoTransactionManager and use @Transactional.bulkOps for many inserts or updates in one round trip.stream (closed in a try-with-resources block) instead of find to avoid loading everything into memory.| Need | Better choice |
|---|---|
| Simple lookups and derived queries | MongoRepository |
Partial updates, upserts, findAndModify | MongoTemplate |
| Aggregations and dynamic filters | MongoTemplate |
| One abstraction with custom methods | Repository plus a custom fragment that uses MongoTemplate |
MongoRepository is a declarative interface where Spring generates the implementation from method names and annotations. MongoTemplate is the lower-level imperative API that repositories use internally, and it gives you full control over queries and updates.
Yes. It is stateless apart from its configuration, so a single instance is shared across threads. The underlying MongoClient manages the connection pool.
No. For non-blocking code use ReactiveMongoTemplate, which returns Mono and Flux instead of blocking results.
Not by default in Spring Boot. Enable auto-index-creation for development or define indexes explicitly for production.
MongoTemplate is the core imperative API of Spring Data MongoDB. It maps documents to Java types, translates errors, and offers Query, Criteria, Update and Aggregation for everything from simple CRUD to pipelines. Use repositories for common cases and MongoTemplate for partial updates, upserts, aggregations and dynamic queries, and use ReactiveMongoTemplate when your application is reactive.