Spring Boot MongoDB Configuration: Easy Steps

• February 9th, 2022


MongoDB is highly elastic and lets you combine and store multivariate data without compromising on the powerful indexing options, data access, and validation rules. On the other hand, Spring Boot is a microframework that is used by the developer community to build stand-alone applications. Spring Boot is an open-sourced application and is useful if you want to develop REST API.

The Spring Boot MongoDB Configuration is part of the Spring Data Project. It aims to create an amicable environment for developers aiming to build a Spring-based programming model. The Spring Boot MongoDB Configuration is a powerful integration you can create new datasets while also keeping hold of “store-specific features and capabilities.”

This tutorial article will discuss the Spring Boot MongoDB Configuration in detail.

Table of Content

  1. What is MongoDB?
  2. What is SpringBoot?
  3. Spring Boot MongoDB Configuration
  4. Conclusion

What is MongoDB?


MongoDB is a document-oriented open-source NoSQL database. It stores the data in documents and supports NoSQL query language to interact with data. MongoDB is very popular among organizations due to its features. 

NoSQL database means it does not store the data in rows and columns compared to traditional databases but instead uses documents that collect key-value pairs to store the data. Key-Value pair allows MongoDB to store the data schemaless and scale them vertically when needed without disrupting the data model. It keeps the data into a storage format known as BSON (Binary Style of JSON document). 

What is Spring Boot?


Spring Boot is a framework that is built on top of the Spring framework. SpringBoot simplifies the Spring framework by providing pluggable dependencies like Spring Kafka, Spring Web Services, Spring Security, and many more. 

Spring Boot is gaining popularity nowadays because it has Java as its programming language, and it helps developers build enterprise-grade applications very quickly with minimal configurations.

Key Features of Spring Boot

  1. Spring Boot applications are auto configurable, which means that they can be configured via a list of dependencies or simply by a properties file. For example, if you list MySQL as a dependency, the SpringBoot application will start with MySQL connector included, which allows you to work seamlessly.
  1. Spring Boot application can run on standalone mode, i.e., on one’s machine/laptop. Users don’t need a separate webserver to deploy the application.
  1. Spring Boot provides many options while configuring, and hence if you include JPA in your Pom.xml, it will automatically configure a memory database, hibernate entity, and sample data source. This feature makes SpringBoot an Opinionated framework.
  1. SpringBoot Framework reduces the overall development time and increases the team’s productivity by avoiding boilerplate code, configurations, and many more.
  1. Spring Boot framework makes it easy for developers to create and test Java-based applications by providing a default setup for unit and integration tests.

Simplify MongoDB ETL Using Hevo’s No-code Data Pipeline!

Hevo Data is a No-code Data Pipeline that offers a fully managed solution to set up Data Integration for 100+ Data Sources (Including 40+ Free sources) and will let you directly load data from sources like MongoDB to a Data Warehouse or the Destination of your choice.

Hevo will automate your data flow in minutes without writing any line of code. Its fault-tolerant architecture makes sure that your data is secure and consistent. Hevo provides you with a truly efficient and fully automated solution to manage data in real-time and always have analysis-ready data. 

Get Started with Hevo for Free

Let’s look at some of the salient features of Hevo:

  • Fully Managed: It requires no management and maintenance as Hevo is a fully automated platform.
  • Data Transformation: It provides a simple interface to perfect, modify, and enrich the data you want to transfer. 
  • Real-Time: Hevo offers real-time data migration. So, your data is always ready for analysis.
  • Schema Management: Hevo can automatically detect the schema of the incoming data and map it to the destination schema.
  • Connectors: Hevo supports 100+ Integrations to SaaS platforms such as WordPress, FTP/SFTP, Files, Databases, BI tools, and Native REST API & Webhooks Connectors. It supports various destinations including Google BigQuery, Amazon Redshift, Snowflake, Firebolt, Data Warehouses; Amazon S3 Data Lakes; Databricks, MySQL, SQL Server, TokuDB, DynamoDB, MongoDB PostgreSQL Databases to name a few.  
  • Secure: Hevo has a fault-tolerant architecture that ensures that the data is handled in a secure, consistent manner with zero data loss.
  • Hevo Is Built To Scale: As the number of sources and the volume of your data grows, Hevo scales horizontally, handling millions of records per minute with very little latency.
  • Live Monitoring: Advanced monitoring gives you a one-stop view to watch all the activities that occur within Data Pipelines.
  • Live Support: Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
Sign up here for a 14-Day Free Trial!

Spring Boot MongoDB Configuration

The Spring Boot MongoDB Configuration is relatively simple and involves few steps for configuration. SpringBoot allows users to interact with MongoDB via two methods, MongoTemplate and MongoRepository.

The MongoTemplate follows the standard template and provides a ready-to-go basic API. The MongoRepository follows the Spring Data-centric approach with more flexible and complex API operations.

In this article, we will focus on interacting with MongoDB via MongoRepository. Let us look at how to perform operations with the Spring Boot MongoDB Configuration

Before going through the steps, let us look at the pre-requisites – 

  1. You need a running MongoDB server. To setup a MongoDB server, you can refer  MongoDB Quick Start guide
  2. Spring Boot framework installed on your machine.

Now that the Spring Boot MongoDB Configuration framework is set up, let us look at the step-by-step approach to configure MongoDB with SpringBoot.

Step 1: Create Spring Project.

  1. Launch SpringBoot STS.
  2. Navigate to File> New > Spring Template Project > Simple Spring Utility Project
  3. Enter the project name and package name (say – org.spring.mongo.demo)
  4. In the pom.xml, add the following dependencies – 

  <!-- other dependency elements omitted -->



Step 2: Setup XML configurations

  1. Now that you have SpringBoot setup, it’s time to configure some XML for MongoDB configuration.
  2. You will find mongoConfig.xml under the src folder in your SpringBoot project.
  3. Update the File with the following information:
<mongo:mongo-client id="mongoClient" host="localhost" />
<mongo:db-factory id="mongoDbFactory" dbname="test" mongo-client-ref="mongoClient" />

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> 
<constructor-arg ref="mongoDbFactory"/> 

<mongo:repositories base-package="org.spring.mongo.demo" mongo-template-ref="mongoTemplate"/>

Step 3: Setup Java Configurations

  1. Now that we have XML’s configured, we need to configure Java classes by extending the base class for MongoDB configuration.
@EnableMongoRepositories(basePackages = "org.spring.mongo.demo")
public class MongoConfig extends AbstractMongoClientConfiguration {

    private final List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();

    protected String getDatabaseName() {
        return "test";

    public MongoClient mongoClient() {
        final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test");
        final MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
        return MongoClients.create(mongoClientSettings);

    public Collection<String> getMappingBasePackages() {
        return Collections.singleton("org.spring.mongo.demo");
  1. Once the configurations are done, create a repository to interact with MongoDB.
public interface UserRepository extends MongoRepository<User, String> {

Step 4: Define simple entity

  1. Define the simple entity User, with the parameter as Name, Age
public class User {

  public String id;

  public String name;

  public User() {}

  public User(String name) {
    this.name = name;


  public String toString() {
    return String.format(
        "User[id=%s, name='%s']",
        id, name);


Step 5: Running CRUD Operations

  1. Once we set up the repository, the repository has several inbuilt methods to perform read-write operations in MongoDB. Some of them are – 
    1. Insert
    2. Save
    3. Update
    4. Delete
  2. Create an application class to run simple queries against MongoDB collection – 
public class AccessingDataMongodbApplication implements CommandLineRunner {

  private UserRepository repository;

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);

  public void run(String args) throws Exception {


	// Add the below codes here to perform CRUD operations



Let ‘s discuss how to implement the Spring Boot MongoDB Configuration.

  1. Insert – 

Insert API inserts a new user in MongoDB collection. Run the below code to see the output.

User user = new User();

The output of the command will be –

    "_id" : ObjectId("xxxxx"),
    "_class" : "org.spring.mongo.demo.model.User",
    "name" : "Jon"
  1. Save-Insert

Save-Insert is similar to insert but has a different API.

User user = new User();

The output of the command will be – 

    "_id" : ObjectId("xxxx"),
    "_class" : "org.spring.mongo.demo.model.User",
    "name" : "Aaron"
  1. Save-Update

Save-Update is an API that updates the existing data in MongoDB.

The initial state of the database is – 

    "_id" : ObjectId("xxxx"),
    "_class" : "org.spring.mongo.demo.model.User",
    "name" : "Roy"

Now we execute the operation:

user = mongoTemplate.findOne(
  Query.query(Criteria.where("name").is("Roy")), User.class);
    "_id" : ObjectId("xxxx"),
    "_class" : "org.spring.mongo.demo.model.User",
    "name" : "Jim"
  1. Delete

Delete API deletes the existing users from the MongoDB collection. 

Here’s the current state of the database – 

    "_id" : ObjectId("xxxx"),
    "_class" : "org.spring.mongo.demo.model.User",
    "name" : "Benn"

Let’s run delete:


And here’s our result:


There are many more in-built APIs available in MongoDB Repository methods. You can get the list of all the methods on the STS console.


In this blog post, we have a detailed step-by-step procedure to enable the Spring Boot MongoDB Configuration.

For better judgment and understanding of the Spring Boot MongoDB Configuration, either of these two articles can help:

  1. Spring Boot Integration with MongoDB Tutorial
  2. Spring Data MongoDB – Reference Documentation
Visit our Website to Explore Hevo

Hevo Data, a No-code Data Pipeline provides you with a consistent and reliable solution to manage data transfer between a variety of sources like MongoDB and the Spring Boot MongoDB Configuration, with a few clicks.

Hevo Data with its strong integration with 100+ sources (including 40+ free sources) allows you to not only export data from your desired data sources & load it to the destination of your choice, but also transform & enrich your data to make it analysis-ready so that you can focus on your key business needs and perform insightful analysis using BI tools.

Want to take Hevo for a spin? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand. You can also have a look at the unbeatable pricing that will help you choose the right plan for your business needs.

Don’t forget to write your experience on the learning and the reading part for the blog, and also write below in the comment section how the Spring Boot MongoDB Configuration was helpful for you or your organization.

No Code Data Pipeline For MongoDB