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.

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). 

Seamlessly Integrate MongoDB with Your Data Destinations Using Hevo

Effortlessly connect MongoDB to your preferred data destinations with Hevo’s intuitive platform. Automate your data workflows and gain real-time insights without the hassle of manual data integration.

Why Choose Hevo for MongoDB Integration?

  • Automated Data Sync: Eliminate manual processes and ensure your data is always up-to-date across all platforms.
  • No-Code Interface: Easily set up and manage your data pipelines with Hevo’s user-friendly interface, no technical expertise required.
  • Real-Time Data Flow: Keep your data fresh and reliable with continuous, real-time updates.

Experience a hassle-free data transfer

Get Started with Hevo for Free

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.

Methods for MongoDB Spring Boot configuration

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. Proper Springboot MongoDB configuration ensures seamless data access in your Java application.

Before understanding how to configure mongodb in spring boot, let us look at the prerequisites: 

  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.

Method 1: MongoDB via MongoRepository

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 – 
<dependencies>

  <!-- other dependency elements omitted -->

  <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>3.3.1</version>
  </dependency>

</dependencies> 

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"/> 
</bean>

<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.
@Configuration
@EnableMongoRepositories(basePackages = "org.spring.mongo.demo")
public class MongoConfig extends AbstractMongoClientConfiguration {

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

    @Override
    protected String getDatabaseName() {
        return "test";
    }

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

    @Override
    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 {

  @Id
  public String id;

  public String name;

  public User() {}

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

  }

  @Override
  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 – 
@SpringBootApplication
public class AccessingDataMongodbApplication implements CommandLineRunner {

  @Autowired
  private UserRepository repository;

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

  @Override
  public void run(String args) throws Exception {

    repository.deleteAll();

	// Add the below codes here to perform CRUD operations

  }

}

Let ‘s discuss how to implement the Spring Boot MongoDB Configuration. Here is a spring boot mongodb configuration example.

  1. Insert – 

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


User user = new User();
user.setName("Jon");
repository.insert(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();
user.setName("Aaron");
repository.save(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);
user.setName("Jim");
repository.save(user);
{
    "_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:

repository.delete(user);

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.

You can read our blog to for more MongoDB real world Use Case examples. 

Method 2: Connecting a Spring Boot application to a MongoDB database via the Spring Data MongoDB library

Step 1: Include the Spring Data MongoDB dependency

The first step is to include the Spring Data MongoDB dependency into your project. This may be achieved by adding the following to your pom.xml file:

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

Step 2: Configure your MongoDB connection

Once the requirement has been installed, you may configure your MongoDB connection by including the following code in your application.Properties or application.yaml file:

spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      database: testdb

This setup instructs Spring Boot to connect to a MongoDB instance on localhost at port 27017 and utilize the testdb database.

Step 3: Create a model class

The next step is to define a model class that represents a MongoDB document. This class should be annotated with the @Document annotation, which informs Spring Data MongoDB that it belongs to a MongoDB collection. Below is an example of a User class:

@Document(collection = "users")
public class User {
    @Id
    private String id;
    private String name;
    private int age;

    // Getters and setters
}

The @Id annotation on the id column informs Spring Data MongoDB that it is the main key for the document. The collection element of the @Document annotation defines the name of the MongoDB collection to which this class corresponds. In this case, the User class maps to a collection called “users”.

Step 4: Create a repository interface

Now that we’ve defined our model class, we can develop a repository interface that extends MongoRepository. The MongoRepository interface supports basic CRUD (create, read, update, and delete) actions on MongoDB documents. Here is an example of a user repository interface:

public interface UserRepository extends MongoRepository<User, String> {
    List<User> findByAge(int age);
}

Step 5: Inject and utilize the repository

In this step, we’ll inject the repository interface from step 4 into our service or controller class and utilize it to connect with the MongoDB database. Here’s an example of injecting and using the repository in a service class:

@Service
public class UserService {

    @Autowired
    private UserRepository repository;

    public void saveUser(User user) {
        repository.save(user);
    }
    public User getUser(String id) {
        return repository.findById(id).orElse(null);
    }
    public List<User> getAllUsers(){
        return repository.findAll();
    }
    public void deleteUser(String id) {
        repository.deleteById(id);
    }
}

Method 3 : Using MongoTemplate

The MongoTemplate class may also be used to conduct updates on specific fields. The wonderful thing about MongoTemplate is that the modification can be performed with a single database interaction. MongoDB configuration Spring Boot also help to simplify the setup of MongoDB in your Spring Boot project

To utilize MongoTemplate, we first establish a custom repository in which we write the update queries.

Let’s create a method for updating the amount of a supermarket item.

Create an interface called CustomItemRepository:

public interface CustomItemRepository {
    
    void updateItemQuantity(String name, float newQuantity);

}

We may add as many methods as we need and supply implementations in the CustomItemRepositoryImpl class.

@Component
public class CustomItemRepositoryImpl implements CustomItemRepository {

    @Autowired
    MongoTemplate mongoTemplate;
    
    public void updateItemQuantity(String name, float newQuantity) {
        Query query = new Query(Criteria.where("name").is(name));
        Update update = new Update();
        update.set("quantity", newQuantity);
        
        UpdateResult result = mongoTemplate.updateFirst(query, update, GroceryItem.class);
        
        if(result == null)
            System.out.println("No documents updated");
        else
            System.out.println(result.getModifiedCount() + " document(s) updated..");

    }

}

MongoTemplate is @Autowired, therefore Spring will inject the object dependencies. The @Component annotation will enable Spring to discover the CustomItemRepository interface.

The next step is to invoke this function from the main class. We’ll define our customRepo in the same way we stated the groceryItemRepo:

     @Autowired
    CustomItemRepository customRepo;

And we’ll need a method in our main class to invoke the customRepo function.

// UPDATE
     public void updateItemQuantity(String name, float newQuantity) {
         System.out.println("Updating quantity for " + name);
         customRepo.updateItemQuantity(name, newQuantity);
     }

Add the following method to the run function and call it when the program is executed:

System.out.println("\n-----UPDATE QUANTITY OF A GROCERY ITEM-----\n");
        
        updateItemQuantity("Bonny Cheese Crackers Plain", 10);

The output should be:

-----UPDATE QUANTITY OF A GROCERY ITEM-----

Updating quantity for Bonny Cheese Crackers Plain
1 document(s) updated..

In the MongoRepository example, we had to do three operations (search, set, and save). In this scenario, we changed the database in a single transaction!

MongoTemplate vs MongoRepository

  • MongoTemplate offers extensive control over data querying and data retrieval from the database.
  • Spring Data repositories offer a user-friendly approach to data retrieval.
  • It’s important to note that MongoTemplate is tied to a specific database. In contrast, Spring Data repositories allow for seamless database switching, enabling you to effortlessly transition to alternative databases like MySQL, Neo4J, or others without such flexibility.

Conclusion

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

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.

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.

FAQs

1. How to configure Spring Boot with MongoDB?

Add spring-boot-starter-data-mongodb dependency, configure MongoDB URI and database details in application.properties, and create a repository interface extending MongoRepository.

2. Where is the MongoDB config file?

MongoDB configuration is typically done in application.properties or application.yml in a Spring Boot application, not a separate config file.

3. How to configure DB properties in Spring Boot?

Set database properties like URL, username, and password in application.properties for MongoDB or other relational databases (e.g., MySQL, PostgreSQL).

Vishal Agrawal
Technical Content Writer, Hevo Data

Vishal Agarwal is a Data Engineer with 10+ years of experience in the data field. He has designed scalable and efficient data solutions, and his expertise lies in AWS, Azure, Spark, GCP, SQL, Python, and other related technologies. By combining his passion for writing and the knowledge he has acquired over the years, he wishes to help data practitioners solve the day-to-day challenges they face in data engineering. In his article, Vishal applies his analytical thinking and problem-solving approaches to untangle the intricacies of data integration and analysis.