Multiple Spring Data MongoDB Connections


Using Spring Data Starter MongoDB to connect to multiple MongoDB databases is quite easy. Its less complicated when you use just MongoTemplate for all your queries. But gets complicated when you use [both MongoTemplate and MongoRepository] ( connects to the intended secondary datasource but MongoRepository still uses the primary(strange but true).

Fortunately there is a simple way to solve it.

1. Create your custom MongoTemplate bean for your secondary datasource.

public Mongo mongo() throws Exception{
 return new MongoClient(host,port);

@Bean(autowire = Autowire.BY_NAME, name = "secondaryMongoTemplate")
public MongoTemplate secondaryMongoTemplate() throws Exception {
	return new MongoTemplate(mongo(),database);

2. And Finally @EnableMongoRepositories with the custom MongoTemplate

    basePackages ={""}, 
    mongoTemplateRef = "secondaryMongoTemplate"

Now all MongoRepository implmentations would use the same datasource configuration as your custom MongoTemplate.

Ok. Later.

Written on October 9, 2015