MongoTemplate is the central class of Spring Data MongoDB for working with a database through code. It wraps the MongoDB Java driver and offers typed methods to insert, query, update and delete documents, mapping them to and from your Java classes.
Use it when you want explicit control over each operation, such as building a Query with Criteria or applying an atomic Update, instead of relying on generated repository methods.
MongoTemplate implements the MongoOperations interface and follows the template pattern, like JdbcTemplate does for SQL. It takes care of:
MappingMongoConverter.DataAccessException hierarchy.Inject the MongoOperations interface when you can, which makes the code easier to mock, or MongoTemplate directly when you need template-specific methods.
The service below uses constructor injection and covers each operation:
Key points in this code:
insert fails if the id already exists. save inserts or replaces by id.Criteria builds the filter, and Update builds partial modifications such as set, inc, push and unset.decreaseStock checks the stock inside the filter and updates in one atomic server-side operation, which avoids a read-modify-write race.UpdateResult and DeleteResult tell you how many documents matched or changed.fields().include(...) returns only the chosen fields, which reduces network traffic for wide documents.
| Need | Repository | MongoTemplate |
|---|---|---|
| Simple find by field | Derived method | Works, more verbose |
Atomic $inc, $push, $set on parts of a document | Limited | Update |
| Aggregation pipelines | @Aggregation for simple cases | Full Aggregation API |
| Dynamic filters built at runtime | Awkward | Criteria built conditionally |
| Bulk writes and index management | No | bulkOps, indexOps |
Both can live in the same project. Repositories give you speed of development, and the template gives you precision.
Yes. After configuration it is thread-safe, so you can share one instance as a singleton bean.
insert always creates a new document and throws on a duplicate id. save replaces the document with that id, or inserts it when none exists.
Yes. With spring-boot-starter-data-mongodb on the classpath and a connection URI configured, Boot registers a MongoTemplate bean.
Yes, on a replica set or sharded cluster, using a MongoTransactionManager and @Transactional. A standalone server does not support them.
MongoTemplate is the programmatic data access API of Spring Data MongoDB. It maps documents, builds queries with Query and Criteria, applies atomic updates with Update, and covers aggregation, bulk and index operations. Use it where repositories are too limiting, and keep repositories for routine CRUD.