How to get Access Two Database from the Same Cluster for Spring Boot Application

I have to access two databases from the Same Cluster. Actually, I’m working with a single database at the moment. I have to access another database from the same cluster in order to perform more aggregation queries for my application. Are there any way to achieve that in Spring Boot

Hi @Abishan_Parameswaran,

You have the answer in my Java Spring Boot MongoDB Starter repository in Github.

In this starter pack, I create the MongoClient bean like this in

public MongoClient mongoClient() {
    CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
    CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
    return MongoClients.create(MongoClientSettings.builder()
                                                      .applyConnectionString(new ConnectionString(connectionString))

Then in the, I inject that bean and initialises the access to my database and collection during the init of this bean using a @PostConstruct. Nothing prevents you from initialising more MongoCollection at this point, using a different DB or not.

public class MongoDBPersonRepository implements PersonRepository {

    private final MongoClient client;
    private MongoCollection<Person> personCollection;

    public MongoDBPersonRepository(MongoClient mongoClient) {
        this.client = mongoClient;

    void init() {
        personCollection = client.getDatabase("test").getCollection("persons", Person.class);

That’s not the only way to do it. But I feel like this is a clean solution.


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.