how to connect 2 mongodb databases in springboot

329 Views Asked by At

I am currently using 1 mongodb. This is how I set it up in application spring.data.mongodb.database=Active spring.data.mongodb.uri=mongodb+srv://<my_uri>

Now I need to introduce a secondary database named Inactive How do I set it up in application? Thank you.

I have tried as below, but it didn't work. spring.data.mongodb.db1.database=Active spring.data.mongodb.db1.uri=mongodb+srv://<my_uri>

spring.data.mongodb.db2.database=Inactive spring.data.mongodb.db2.uri=mongodb+srv://<my_uri>

I keep <my_uri> the same for both Active and Inactive, because I think it is the cluster'uri and both databases are inside the cluster.

1

There are 1 best solutions below

2
John Williams On

You need to create a second data source and wire it in to template etc. It is a variant of this.

mongodb.primary.host= mongodb+srv://<my_uri>
mongodb.primary.database=Active
mongodb.primary.authenticationDatabase=admin
mongodb.primary.username=user1
mongodb.primary.password=password
mongodb.primary.port=27017

mongodb.secondary.host= mongodb+srv://<my_uri>
mongodb.secondary.database=Inactive
mongodb.secondary.authenticationDatabase=admin
mongodb.secondary.username=user1
mongodb.secondary.password=password
mongodb.secondary.port=27017