1

In my spring boot application, i need to include two mongo databases and use each database for different MongoRepository. Currently i have configured my mongodb configuration in a yml file. I need to add the other database configuration to this same yml file and specify the using database in each repository.

the yml file :

spring:
  data:
mongodb:
  host: 127.0.0.1
  port: 27017
  database: db_admin_crm
  rest:
  base-path: /crm

The repository :

 @RepositoryRestResource(collectionResourceRel = "webinarSignups",path = "webinarSignups")
 public interface WebinarSignupsRepository extends MongoRepository<WebinarSignUp,String> {

}

Ideas will be appreciated. Thanks.

1

1 Answer 1

1

You can use a custom configuration similar to:

first:
  host: 127.0.0.1
  port: 27017
  database: first

second:
  host: 127.0.0.1
  port: 27018
  database: second

And use this properties in a custom configuration file

@Configuration 
public class MongoConfiguration {

    @Value("${first.host}")
    private String firstHost;

    ...

    @Bean(name = "firstMongoTemplate")
    public MongoTemplate firstMongoTemplate() throws Exception {
       // Return a MongoTemplate created using the first properties

       ...
    }

}

and use it as follow:

@Repository
public class FirstMongoRepository {

    @Autowired
    @Qualifier("firstMongoTemplate")
    private MongoTemplate mongoTemplate;



    ...
}

Note that this approach can be used for any configuration that needs multiple objects of the same type, for example multiple DataSource (if you have multiple databases), multiple ObjectMapper (if you need distinct kind of serialization)...

Sign up to request clarification or add additional context in comments.

3 Comments

I updated the question. is there a way to do this without using the MongoTemplate?
@GeekySelene you can do it with any Mongo class related, for example You can use MongoClient or DB
Thanks for the answer. I set up the configuration but i run into a exception when I try to send GET request to the REST endpoint. Please see here. stackoverflow.com/questions/56041911/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.