Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

383
Views
Spring Boot Accessing Multiple Mongo Databases using repositories

I have a spring boot tenant application that needs to access multiple tenant databases. All of the databases are on a single MongoDB server. Each tenant has there own database that is password protected. I have been able to get it to work using MongoClient as shown below.

 MongoClient mongoClient = new MongoClient(mongoConnectionUri,
   mongoCredentials);
 DB tenantDB = mongoClient.getDB(tenantWebRequest.getNewTenantId());

MongoClient is simple to use and as shown above and can easily connect to runtime mongo databases. However, MongoClient is programmatically clumsy when writing/query documents to the database. I would rather use MongoRespository with its very powerful CRUD and custom query methods. Here is the code for a single MongoDB Repository

 public class MongoConfig extends AbstractMongoConfiguration {

@Override
protected String getDatabaseName() {
    return mongodbname;
}

@Override
public Mongo mongo() throws Exception {

    return new MongoClient(mongoconnectionuri, mongoport);

}

// Mongo Connection URI
@Value("${spring.data.mongodb.uri}") 
private String mongoconnectionuri;

// Mongo Connection Port
@Value("${spring.data.mongodb.port}")
private int mongoport;

// Mongo Tenant Authorization database
@Value("${spring.data.mongodb.database}") 
private String mongodbname;

}

The repository looks like,

public interface UserRepository extends MongoRepository< Tenant, String>{

    public User findByTenantname(String tenantname);

    } 

This repository works great for a single static database. How do I get repositories to work where I can create and access at runtime different tenant databases? I don't know the names of the tenants ahead of time. When a new tenant signs up for the service they access a web service and type in their new tenant name. I use the name and create a new tenant database with several collections initialized with customer metadata. I am using spring boot with annotations along with Gradle.

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!