Spring Boot with Embedded MongoDB

Spring Boot with Embedded MongoDB

7 Comments

Recently we’ve seen a rise in popularity of NoSQL databases. MongoDB has rapidly gained popularity in the enterprise and the Spring community.

While developing and testing Spring Boot applications with MongoDB as the data store, it is common to use the lightweight Embedded MongoDB rather than running a full-fledged server. As the embedded MongoDB runs in memory, it is blazing fast and will save you lot of time both during development and running your tests, in your development machine or a CI server.

I have covered setting up MongoDB in a Spring Boot application here.

In this post, I’ll discuss how to use embedded MongoDB in a Spring Boot application.

I posted a video here that explains the Spring Boot application that I’ll use in this post.

The Maven POM

Embedded MongoDB downloads and fires-up a real MongoDB instance. You get the benefit of talking to an instance loaded in memory with the same capabilities as your production environment. The Maven POM dependency to include Embedded MongoDB is this:

<dependency>
    <groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo</artifactId>
    <version>1.50.5</version>
</dependency>

You also need to include the embedmongo-spring dependency that provides Spring Factory Bean for Embedded MongoDB, like this.

<dependency>
    <groupId>cz.jirutka.spring</groupId>
    <artifactId>embedmongo-spring</artifactId>
    <version>RELEASE</version>
</dependency>

Finally, with this spring-boot-starter-data-mongodb dependency pulled in, you should be all set to use embedded MongoDB in your Spring Boot app.

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

The complete pom.xml is this.

pom.xml

   //

    4.0.0

    guru.springframework
    spring-boot-mongodb
    0.0.1-SNAPSHOT
    jar

    spring-boot-mongodb
    Demo project for Spring Boot and Mongo DB

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.0.M7
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            de.flapdoodle.embed
            de.flapdoodle.embed.mongo
            1.50.5
        
        
            cz.jirutka.spring
            embedmongo-spring
            RELEASE
        
        
            org.springframework.boot
            spring-boot-starter-data-mongodb
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

	
		
			spring-snapshots
			Spring Snapshots
			https://repo.spring.io/snapshot
			
				true
			
		
		
			spring-milestones
			Spring Milestones
			https://repo.spring.io/milestone
			
				false
			
		
	

	
		
			spring-snapshots
			Spring Snapshots
			https://repo.spring.io/snapshot
			
				true
			
		
		
			spring-milestones
			Spring Milestones
			https://repo.spring.io/milestone
			
				false
			
		
	

The MongoDB Config

You need to provide a MongoTemplate bean to SpringBoot for your application to interact with the embedded MongoDB instance. You typically use a @Configuration class, like this.

MongoConfig.java

   //package guru.springframework.config;

import java.io.IOException;
import cz.jirutka.spring.embedmongo.EmbeddedMongoFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.*;
import com.mongodb.MongoClient;


@Configuration
public class MongoConfig {

    private static final String MONGO_DB_URL = "localhost";
    private static final String MONGO_DB_NAME = "embeded_db";
    @Bean
    public MongoTemplate mongoTemplate() throws IOException {
        EmbeddedMongoFactoryBean mongo = new EmbeddedMongoFactoryBean();
        mongo.setBindIp(MONGO_DB_URL);
        MongoClient mongoClient = mongo.getObject();
        MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, MONGO_DB_NAME);
        return mongoTemplate;
    }
}

In this MongoConfig class, EmbeddedMongoFactoryBean is a FactoryBean for Embedded MongoDB that runs MongoDB as a managed process and exposes preconfigured instance of MongoClient.

This is all you need to do to start using Embedded MongoDB in a Spring Boot application.

Note: By default your application will connect to the test database. For a different database, set the spring.data.mongodb.database property in your application.properties configuration file.

You can download the source code from git here.

About jt

    You May Also Like

    7 comments on “Spring Boot with Embedded MongoDB

    1. February 26, 2018 at 2:50 am

      Nicely Explained , Thanks for this .

      Reply
    2. April 30, 2018 at 6:51 pm

      Hi. But if I declare that MongoTemplate you’ve shown my application will ALWAYS use the embedded mongo, even when I’m not running tests, correct? what if I want it to use embedded mongo only when I’m running Junit?

      Reply
    3. August 11, 2018 at 8:05 am

      use spring profile for testing @TestPropertySource(“classpath:test.properties”)
      @ActiveProfiles({“testing”})

      Reply
    4. September 24, 2019 at 9:06 am

      How can i access the mongoDb to look up what has been persisted?

      Reply
      • September 24, 2019 at 2:29 pm

        This Application with mongo is not working the products are not being saved when i restart the server where are the entries?

        Reply
    5. March 25, 2020 at 3:37 pm

      Having also few test cases with correct annotations as example would help. Without those this was not helpful at all at least for me.

      Reply

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.