Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

385
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda