Spring Boot with Embedded MongoDB

Spring Boot with Embedded MongoDB


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:

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

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.

The complete pom.xml is this.


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.


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

    3 comments on “Spring Boot with Embedded MongoDB

    1. February 26, 2018 at 2:50 am

      Nicely Explained , Thanks for this .

    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?

    3. August 11, 2018 at 8:05 am

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


    Leave a Reply