In Spring Boot, MongoTemplate is the bean you inject when you want direct, programmatic control over MongoDB operations. Boot auto-configures it from your connection properties, so you can run custom queries, aggregations and partial updates without writing any configuration class.
Repositories cover routine CRUD. MongoTemplate is for everything where you need to shape the query or the update yourself.
Add the starter to your build:
Then set the connection in application.properties:
With the starter on the classpath, MongoDataAutoConfiguration creates a MongoClient, a MongoDatabaseFactory and a MongoTemplate bean. You normally do not define the bean yourself. Defining your own MongoTemplate bean makes Boot back off, which is only needed for special cases such as a second database.
Constructor injection is preferred over @Autowired fields because it makes dependencies explicit and the class easy to test.
Because Query is an ordinary object, you can add conditions in an if block when a filter is optional, which is the clean way to implement search forms with many optional fields.
Aggregation is where MongoTemplate clearly outperforms derived repository methods. The example totals quantity per warehouse:
The group stage output uses _id for the group key, which Spring maps to the id component of the result record.
findAndModify updates and returns the document in a single atomic step, and upsert(true) creates it when it does not exist.
When one application talks to two databases, define a second MongoDatabaseFactory and MongoTemplate with their own properties and mark one as @Primary. Boot's auto-configuration stops creating its own template as soon as you declare yours.
No. With the starter and spring.data.mongodb.uri, Boot creates one. Declare your own only to change its behaviour or to add a second database.
Use repositories for plain CRUD and simple derived queries. Use MongoTemplate for aggregations, dynamic filters, partial updates and bulk operations.
Yes. They share the same converter and database factory, so documents written by one are read by the other.
Set logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG to see the queries and updates.
Spring Boot gives you a ready MongoTemplate from a single connection property. Inject it with the constructor, use Query, Criteria and Update for precise operations, and use the Aggregation API for reporting. Combine it with repositories where each fits best.