How to connect multiple Mongo DB Databases with Spring Boot

hasanga lakdinu
4 min readSep 5, 2021

hello everyone, in this article, we will discuss how to connect two different Mongo DB databases into one single spring boot project, for that one i have created simple spring boot project.

if you prefer video over article related video tutorial is here,

otherwise, below is the pom.xml file for that one.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>multi_mongo_proj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>multi_mongo_proj</name>
<description>multi_mongo_proj</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

then in application.properties file i added these properties.

spring.autoconfigure.exclude= org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration

server.port = 8090

spring.data.mongodb.newdb1.uri=mongodb://0.0.0.0:27020/newdb1
spring.data.mongodb.newdb2.uri=mongodb://0.0.0.0:27020/newdb2

before go ahead i will show you how my folder structure is.

then im going to create a package called configurations. and there i will be creating a file called MultipleMongoConfig.java

//MultipleMongoConfig.java
package com.example.multi_mongo_proj.configurations;

import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

@Configuration
public class MultipleMongoConfig {
@Primary
@Bean(name = "newdb1Properties")
@ConfigurationProperties(prefix = "spring.data.mongodb.newdb1")
public MongoProperties getNewDb1Props() throws Exception {
return new MongoProperties();
}

@Bean(name = "newdb2Properties")
@ConfigurationProperties(prefix = "spring.data.mongodb.newdb2")
public MongoProperties getNewDb2Props() throws Exception {
return new MongoProperties();
}

@Primary
@Bean(name = "newdb1MongoTemplate")
public MongoTemplate newdb1MongoTemplate() throws Exception {
return new MongoTemplate(newdb1MongoDatabaseFactory(getNewDb1Props()));
}

@Bean(name ="newdb2MongoTemplate")
public MongoTemplate newdb2MongoTemplate() throws Exception {
return new MongoTemplate(newdb2MongoDatabaseFactory(getNewDb2Props()));
}

@Primary
@Bean
public MongoDatabaseFactory newdb1MongoDatabaseFactory(MongoProperties mongo) throws Exception {
return new SimpleMongoClientDatabaseFactory(
mongo.getUri()
);
}

@Bean
public MongoDatabaseFactory newdb2MongoDatabaseFactory(MongoProperties mongo) throws Exception {
return new SimpleMongoClientDatabaseFactory(
mongo.getUri()
);
}

}

you can use any name for the beans and methods, prefixes for getNewDb1Props() and getNewDb2Props() are coming from application. properties file(database uris).

then im going to create a Repository package (in this tutorial im not going to create controllers and service classes, just for the demonstration purpose i will only show you how models are created in the Database).

in this repository package i will create modelRepo1 package and modelRepo2 packages.

in modelRepo1 package i will create Model1.java class and Model1Repository interface.

//Model1.java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection="model_1")
@ToString
public class Model1 {

@Id
private String id;
private String name;

}

Model1Repository is an interface that extends MongoRepository interface.

import org.springframework.data.mongodb.repository.MongoRepository;


public interface Model1Repository extends MongoRepository<Model1,String> {
}

similar thing in the modelRepo2Package

//Model2.java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection="model_1")
@ToString
public class Model2 {
@Id
private String id;
private String name;

}

and

//Model2Repository.java
import org.springframework.data.mongodb.repository.MongoRepository;

public interface Model2Repository extends MongoRepository<Model2,String> {
}

then again in configuration package we have to create 2 files

//NewDb1Config.javaimport org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = {"com.example.multi_mongo_proj.repository.modelRepo1"},
mongoTemplateRef = NewDb1Config.MONGO_TEMPLATE
)
public class NewDb1Config {
protected static final String MONGO_TEMPLATE = "newdb1MongoTemplate";
}

in this NewDb1Config.java we have to provide what are the base packages relevant to Database 1, so in my case com.example.multi_mongo_proj.repository.modelRepo1

this package is for the database 1, then

//NewDb2Config.java
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = {"com.example.multi_mongo_proj.repository.modelRepo2"},
mongoTemplateRef = NewDb2Config.MONGO_TEMPLATE
)
public class NewDb2Config {
protected static final String MONGO_TEMPLATE = "newdb2MongoTemplate";
}

okay now the implementation part is over now we have to do is check whether our application is working for that i go to main java class in the application

in my case it is MultiMongoProjApplication

import com.example.multi_mongo_proj.repository.modelRepo1.Model1;
import com.example.multi_mongo_proj.repository.modelRepo1.Model1Repository;
import com.example.multi_mongo_proj.repository.modelRepo2.Model2;
import com.example.multi_mongo_proj.repository.modelRepo2.Model2Repository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.List;

@Slf4j
@SpringBootApplication
public class MultiMongoProjApplication implements CommandLineRunner {

@Autowired
private Model1Repository model1Repository;

@Autowired
private Model2Repository model2Repository;

public static void main(String[] args) {
SpringApplication.run(MultiMongoProjApplication.class, args);
}


@Override
public void run(String... args) throws Exception {
log.info("************************************************************");
log.info("Start creating and printing mongo objects");
log.info("************************************************************");

this.model1Repository.save(new Model1(null,"Model 1 obj"));
this.model2Repository.save(new Model2(null,"Model 2 Obj"));

List<Model1> model1s = this.model1Repository.findAll();
for (Model1 model1obj : model1s) {
log.info(model1obj.toString());
}


List<Model2> model2s = this.model2Repository.findAll();
for (Model2 model2obj : model2s) {
log.info(model2obj.toString());
}

log.info("************************************************************");
log.info("Ended printing mongo objects");
log.info("************************************************************");

}
}

im going to add to objects for model 1 and mode 2, then save it to Database and print them in console.

now we have to run the application. in the console we can see

************************************************************ Start creating and printing mongo objects ************************************************************
Opened connection [connectionId{localValue:5, serverValue:49}] to 0.0.0.0:27020
Opened connection [connectionId{localValue:6, serverValue:50}] to 0.0.0.0:27020Model1(id=6134411e9a84852bf25403cf, name=Model 1 obj)Model2(id=6134411e9a84852bf25403d0, name=Model 2 Obj)************************************************************ Ended printing mongo objects************************************************************

objects have created and those are printed.. so our code is working fine.

Source code: https://github.com/HasangaLakdinu/springboot_mongo

so thats it for this tutorial, hop it will useful for you. see you in next article, until then Happy Coding!!!.

--

--