MongoDB Multi-User Ability (Java): How to switch MongoDB databases with different DB credentials at runtime using MongoClient?


I ran into the problem of multivolume MongoDB. I have two different mongoDB databases (db1 and db2). They have different credentials.

db1 credentials :
userName: admin
password: passwd

db2 credentials :
username: admin1
password: passwd1

I need to switch from one database to another at runtime. I have an autwired mongoTemplate with db1 credentials, but now I cannot update the template with db2 credentials. Is it possible? If so, how? If not, tell me another way to switch databases at runtime with different credentials.

Note what I know about "SimpleMongoDbFactory". You can extend "SimpleMongoDbFactory" and can override the "getDb" method and pass the required dbName name to super.getDb ("dbName") for layering. But this does not work with two databases with different credentials.

+5
source share
2 answers

What if you create a MongoCredential for each database and pass them to MongoClient , which you pass to SimpleMongoDbFactory

  MongoCredential credential1 = MongoCredential.createCredential("admin", db1, "password"); MongoCredential credential2 = MongoCredential.createCredential("admin1", db2, "password1"); MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential1, credential2)); 
+4
source

Create independent instances of MongoTemplate, each of which has its own credentials and selects the appropriate ones at runtime.

Each connection is established using credentials, so if you change them to an existing connection, you essentially destroy the connection and create a new one, and you won’t take advantage of the union.

0
source

Source: https://habr.com/ru/post/1262223/


All Articles