{"id":3757,"date":"2025-12-23T10:00:21","date_gmt":"2025-12-23T15:00:21","guid":{"rendered":"https:\/\/www.mymiller.name\/wordpress\/?p=3757"},"modified":"2025-12-23T10:00:21","modified_gmt":"2025-12-23T15:00:21","slug":"connecting-to-multiple-mongodb-databases-with-spring-data","status":"publish","type":"post","link":"https:\/\/www.mymiller.name\/wordpress\/spring_databases\/connecting-to-multiple-mongodb-databases-with-spring-data\/","title":{"rendered":"Connecting to Multiple MongoDB Databases with Spring Data"},"content":{"rendered":"\n<div class=\"wp-block-jetpack-markdown\"><p>Modern applications, especially in a microservices architecture, often require interaction with multiple databases. This is particularly common with NoSQL databases like MongoDB, where different services might have their own dedicated databases. Spring Data MongoDB simplifies the management of multiple MongoDB datasources within your application. This article provides a comprehensive guide to achieve this.<\/p>\n<p><strong>1. Project Setup and Dependencies<\/strong><\/p>\n<p>Begin with a Spring Boot project and add the necessary MongoDB driver and Spring Data MongoDB dependencies in your <code>pom.xml<\/code> (Maven) or <code>build.gradle<\/code> (Gradle):<\/p>\n<pre><code class=\"language-xml\">&lt;dependency&gt;\n    &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n    &lt;artifactId&gt;spring-boot-starter-data-mongodb&lt;\/artifactId&gt;\n&lt;\/dependency&gt;\n<\/code><\/pre>\n<p><strong>2. Configuration with <code>application.yml<\/code><\/strong><\/p>\n<p>Leverage Spring Boot\u2019s externalized configuration by defining your database connection details in an <code>application.yml<\/code> file:<\/p>\n<pre><code class=\"language-yaml\">spring:\n  data:\n    mongodb:\n      first:\n        uri: mongodb:\/\/localhost:27017\/firstdb\n        # Add authentication details if needed\n        # username: your-username\n        # password: your-password\n      second:\n        uri: mongodb:\/\/localhost:27017\/seconddb\n        # Add authentication details if needed\n        # username: your-username\n        # password: your-password\n<\/code><\/pre>\n<p>This configuration sets up two distinct MongoDB connections, \u201cfirst\u201d and \u201csecond,\u201d each specifying the <code>uri<\/code> with the database host, port, and database name. Include <code>username<\/code> and <code>password<\/code> if your databases require authentication.<\/p>\n<p><strong>3. Defining Multiple Configurations<\/strong><\/p>\n<p>Create separate configuration classes for each MongoDB database to manage connections effectively. In each class, define the connection details by referencing the <code>application.yml<\/code> properties and specify the packages to scan for Spring Data repositories.<\/p>\n<pre><code class=\"language-java\">@Configuration\n@EnableMongoRepositories(basePackages = &quot;com.example.repository.first&quot;, \n                       mongoTemplateRef = &quot;firstMongoTemplate&quot;)\npublic class FirstMongoConfig {\n\n    @Value(&quot;${spring.data.mongodb.first.uri}&quot;)\n    private String firstMongoUri;\n\n    @Bean\n    @Primary\n    public MongoTemplate firstMongoTemplate() throws Exception {\n        return new MongoTemplate(firstMongoFactory());\n    }\n\n    @Bean\n    @Primary\n    public MongoDatabaseFactory firstMongoFactory() throws Exception {\n        return new SimpleMongoClientDatabaseFactory(new ConnectionString(firstMongoUri));\n    }\n}\n\n@Configuration\n@EnableMongoRepositories(basePackages = &quot;com.example.repository.second&quot;, \n                       mongoTemplateRef = &quot;secondMongoTemplate&quot;)\npublic class SecondMongoConfig {\n\n    @Value(&quot;${spring.data.mongodb.second.uri}&quot;)\n    private String secondMongoUri;\n\n    @Bean\n    public MongoTemplate secondMongoTemplate() throws Exception {\n        return new MongoTemplate(secondMongoFactory());\n    }\n\n    @Bean\n    public MongoDatabaseFactory secondMongoFactory() throws Exception {\n        return new SimpleMongoClientDatabaseFactory(new ConnectionString(secondMongoUri));\n    }\n}\n<\/code><\/pre>\n<p>In this example:<\/p>\n<ul>\n<li><code>@EnableMongoRepositories<\/code>: Specifies the base package for repositories using this configuration.<\/li>\n<li><code>mongoTemplateRef<\/code>: Links the repositories to the correct <code>MongoTemplate<\/code>.<\/li>\n<li>Separate <code>MongoTemplate<\/code> and <code>MongoDatabaseFactory<\/code> beans are defined for each database.<\/li>\n<li><code>@Primary<\/code> annotation on the \u201cfirst\u201d configuration sets it as the default.<\/li>\n<li><code>@Value<\/code> injects the URI from <code>application.yml<\/code> into the respective variables.<\/li>\n<\/ul>\n<p><strong>4. Creating Repositories<\/strong><\/p>\n<p>Create separate packages for repositories interacting with each database, e.g., <code>com.example.repository.first<\/code> and <code>com.example.repository.second<\/code>. Define your repository interfaces within those packages:<\/p>\n<pre><code class=\"language-java\">package com.example.repository.first;\n\nimport com.example.model.FirstModel;\nimport org.springframework.data.mongodb.repository.MongoRepository;\n\npublic interface FirstRepository extends MongoRepository&lt;FirstModel, String&gt; {\n    \/\/ ... your repository methods ...\n}\n\npackage com.example.repository.second;\n\nimport com.example.model.SecondModel;\nimport org.springframework.data.mongodb.repository.MongoRepository;\n\npublic interface SecondRepository extends MongoRepository&lt;SecondModel, String&gt; {\n    \/\/ ... your repository methods ...\n}\n<\/code><\/pre>\n<p><strong>5. Injecting and Using Repositories<\/strong><\/p>\n<p>Inject your repositories into your service classes and use them as needed:<\/p>\n<pre><code class=\"language-java\">@Service\npublic class MyService {\n\n    @Autowired\n    private FirstRepository firstRepository;\n\n    @Autowired\n    private SecondRepository secondRepository;\n\n    \/\/ ... your service methods ...\n}\n<\/code><\/pre>\n<p><strong>Important Considerations:<\/strong><\/p>\n<ul>\n<li><strong>Transactions:<\/strong> MongoDB supports multi-document transactions within a single database, but not across multiple databases.<\/li>\n<li><strong>Connection Pooling:<\/strong> Configure appropriate connection pooling for each datasource to optimize performance.<\/li>\n<li><strong>Error Handling:<\/strong> Implement robust error handling for connection failures and other issues.<\/li>\n<\/ul>\n<p>By following these steps, you can effectively manage multiple MongoDB datasources in your Spring application. This approach provides flexibility and scalability, allowing you to design your application with clear separation of concerns and data access.<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":3758,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_coblocks_attr":"","_coblocks_dimensions":"","_coblocks_responsive_height":"","_coblocks_accordion_ie_support":"","jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[435],"tags":[69,319],"series":[],"class_list":["post-3757","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-spring_databases","tag-java-2","tag-spring"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/10\/ai-generated-8180209_1280-jpg.avif","jetpack-related-posts":[{"id":3502,"url":"https:\/\/www.mymiller.name\/wordpress\/spring_databases\/spring-data-jpa-for-dummies-persisting-data-like-a-pro\/","url_meta":{"origin":3757,"position":0},"title":"Spring Data JPA for Dummies: Persisting Data Like a Pro","author":"Jeffery Miller","date":"December 24, 2025","format":false,"excerpt":"Ever feel bogged down by writing tons of code just to interact with your database? If you're a Java developer working with relational databases, Spring Data JPA is your new best friend. This blog post will give you a beginner-friendly introduction to Spring Data JPA, showing you how to save\u2026","rel":"","context":"In &quot;Spring Databases&quot;","block_context":{"text":"Spring Databases","link":"https:\/\/www.mymiller.name\/wordpress\/category\/spring_databases\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/binary-2904980_1280.jpg?fit=1200%2C674&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/binary-2904980_1280.jpg?fit=1200%2C674&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/binary-2904980_1280.jpg?fit=1200%2C674&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/binary-2904980_1280.jpg?fit=1200%2C674&ssl=1&resize=700%2C400 2x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/binary-2904980_1280.jpg?fit=1200%2C674&ssl=1&resize=1050%2C600 3x"},"classes":[]},{"id":3695,"url":"https:\/\/www.mymiller.name\/wordpress\/spring_aop\/boosting-performance-tracking-method-access-with-spring-aop-security-and-a-high-performance-database\/","url_meta":{"origin":3757,"position":1},"title":"Boosting Performance: Tracking Method Access with Spring AOP, Security, and a High-Performance Database","author":"Jeffery Miller","date":"November 24, 2025","format":false,"excerpt":"In our previous blog post, we explored how to track method access in Spring using AOP, Security, and JPA. While that approach provides a solid foundation, let\u2019s now take it a step further by enhancing performance and capturing additional valuable information, such as method execution time. We\u2019ll also switch to\u2026","rel":"","context":"In &quot;Spring AOP&quot;","block_context":{"text":"Spring AOP","link":"https:\/\/www.mymiller.name\/wordpress\/category\/spring_aop\/"},"img":{"alt_text":"","src":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/09\/money-2173148_1280-jpg.avif","width":350,"height":200,"srcset":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/09\/money-2173148_1280-jpg.avif 1x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/09\/money-2173148_1280-jpg.avif 1.5x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/09\/money-2173148_1280-jpg.avif 2x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/09\/money-2173148_1280-jpg.avif 3x"},"classes":[]},{"id":3928,"url":"https:\/\/www.mymiller.name\/wordpress\/spring_databases\/%f0%9f%92%a1-implementing-cqrs-with-spring-boot-and-kafka\/","url_meta":{"origin":3757,"position":2},"title":"\ud83d\udca1 Implementing CQRS with Spring Boot and Kafka","author":"Jeffery Miller","date":"November 21, 2025","format":false,"excerpt":"As a software architect, I constantly look for patterns that enhance the scalability and maintainability of microservices. The Command Query Responsibility Segregation (CQRS) pattern is a powerful tool for this, especially when coupled with event-driven architecture (EDA) using Apache Kafka. CQRS separates the application into two distinct models: one for\u2026","rel":"","context":"In &quot;Spring Databases&quot;","block_context":{"text":"Spring Databases","link":"https:\/\/www.mymiller.name\/wordpress\/category\/spring_databases\/"},"img":{"alt_text":"","src":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2025\/11\/data-2899902_1280.avif","width":350,"height":200,"srcset":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2025\/11\/data-2899902_1280.avif 1x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2025\/11\/data-2899902_1280.avif 1.5x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2025\/11\/data-2899902_1280.avif 2x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2025\/11\/data-2899902_1280.avif 3x"},"classes":[]},{"id":3846,"url":"https:\/\/www.mymiller.name\/wordpress\/spring_databases\/speed-and-reliability-unit-testing-with-mongodb-memory-server-in-spring-boot\/","url_meta":{"origin":3757,"position":3},"title":"Speed and Reliability: Unit Testing with MongoDB Memory Server in Spring Boot","author":"Jeffery Miller","date":"December 24, 2025","format":false,"excerpt":"When you\u2019re building Spring Boot applications that interact with MongoDB, ensuring the reliability of your data access layer is crucial. Unit tests play a vital role, but setting up and tearing down a real MongoDB instance for each test can be slow and cumbersome. This is where MongoDB Memory Server\u2026","rel":"","context":"In &quot;Spring Databases&quot;","block_context":{"text":"Spring Databases","link":"https:\/\/www.mymiller.name\/wordpress\/category\/spring_databases\/"},"img":{"alt_text":"","src":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2025\/04\/scientist-9234951_1280-png.avif","width":350,"height":200,"srcset":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2025\/04\/scientist-9234951_1280-png.avif 1x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2025\/04\/scientist-9234951_1280-png.avif 1.5x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2025\/04\/scientist-9234951_1280-png.avif 2x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2025\/04\/scientist-9234951_1280-png.avif 3x"},"classes":[]},{"id":3539,"url":"https:\/\/www.mymiller.name\/wordpress\/spring_databases\/spring-data-cassandra-simplifying-java-development-with-apache-cassandra\/","url_meta":{"origin":3757,"position":4},"title":"Spring Data Cassandra: Simplifying Java Development with Apache Cassandra","author":"Jeffery Miller","date":"September 22, 2025","format":false,"excerpt":"Apache Cassandra is a powerful NoSQL database known for its scalability and high availability. Spring Data Cassandra seamlessly integrates Spring\u2019s familiar programming model with Cassandra, boosting developer productivity. Why Spring Data Cassandra? Simplified Configuration: Spring Boot auto-configuration minimizes manual setup. Object-Relational Mapping (ORM): Easily map Java objects to Cassandra tables.\u2026","rel":"","context":"In &quot;Spring Databases&quot;","block_context":{"text":"Spring Databases","link":"https:\/\/www.mymiller.name\/wordpress\/category\/spring_databases\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/network-3396348_1280.jpg?fit=1200%2C720&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/network-3396348_1280.jpg?fit=1200%2C720&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/network-3396348_1280.jpg?fit=1200%2C720&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/network-3396348_1280.jpg?fit=1200%2C720&ssl=1&resize=700%2C400 2x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/network-3396348_1280.jpg?fit=1200%2C720&ssl=1&resize=1050%2C600 3x"},"classes":[]},{"id":3651,"url":"https:\/\/www.mymiller.name\/wordpress\/spring_tracing\/spring-micrometer-tracing-and-observability-made-easy\/","url_meta":{"origin":3757,"position":5},"title":"Spring Micrometer: Tracing and Observability Made Easy","author":"Jeffery Miller","date":"December 24, 2025","format":false,"excerpt":"Observability is crucial for modern applications, allowing you to understand their behavior and performance. Spring Boot 3 introduces powerful observability features through Micrometer. Understanding Observability Observability involves collecting metrics, logs, and traces to provide insights into your running application. Micrometer is the core of this in Spring Boot, offering: Metrics:\u2026","rel":"","context":"In &quot;Spring Tracing &amp; Observability&quot;","block_context":{"text":"Spring Tracing &amp; Observability","link":"https:\/\/www.mymiller.name\/wordpress\/category\/spring_tracing\/"},"img":{"alt_text":"","src":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/08\/art-6749527_1280-jpg.avif","width":350,"height":200,"srcset":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/08\/art-6749527_1280-jpg.avif 1x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/08\/art-6749527_1280-jpg.avif 1.5x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/08\/art-6749527_1280-jpg.avif 2x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/08\/art-6749527_1280-jpg.avif 3x"},"classes":[]}],"jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts\/3757","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/comments?post=3757"}],"version-history":[{"count":1,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts\/3757\/revisions"}],"predecessor-version":[{"id":3759,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts\/3757\/revisions\/3759"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/media\/3758"}],"wp:attachment":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/media?parent=3757"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/categories?post=3757"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/tags?post=3757"},{"taxonomy":"series","embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/series?post=3757"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}