Connecting Spring Boot With MongoDB

Topics Covered

Overview

In this article, we are going to learn about connecting Mongodb and spring boot. Before getting started with the topic, let us get a short overview about the topic.

Connecting Spring Boot with MongoDB:
Spring Boot is a popular Java-based framework for building web applications and microservices. MongoDB is a NoSQL database that provides high performance, scalability, and flexibility for storing and querying data. Integrating Spring Boot with MongoDB is a straightforward process that can be achieved using various libraries and tools. Integrating Spring Boot with MongoDB allows you to take advantage of MongoDB's powerful features while leveraging Spring Boot's ease of use and flexibility.

So let us now begin with the main agenda of our article, Creating Spring Boot MongoDB project.

How Can we use Spring Boot with MongoDB?

Integrating Mongodb and spring boot is a straightforward process that can be achieved using various libraries and tools.

MongoTemplate and MongoRepository are two commonly used ways to interact with the MongoDB Spring Boot application.

MongoTemplate is a class provided by Spring Data MongoDB that offers a rich set of methods for performing operations on MongoDB collections in our Mongodb spring boot application. It provides a low-level API for interacting with the MongoDB database, allowing you to execute queries and commands directly against the database. With MongoTemplate, you can perform various operations such as insert, update, delete, find, aggregate, and map-reduce in our Mongodb spring boot application. It also supports features like pagination, sorting, and geo-spatial queries. However, using MongoTemplate requires more boilerplate code and is less convenient than using a repository.

On the other hand, MongoRepository is an interface provided by Spring Data MongoDB that provides a higher-level abstraction for performing database operations in our Mongodb spring boot application. It extends the basic CRUD operations provided by the CrudRepository interface and provides additional methods for querying and manipulating data in MongoDB. With MongoRepository, you can define custom query methods using method names or annotations, and it will generate the appropriate MongoDB query at runtime. This makes it easier to perform common database operations, and reduces the amount of boilerplate code you need to write in our Mongodb spring boot application. However, it can be less flexible for complex queries that require advanced MongoDB features.

Getting Started

To get started with MongoDB and Spring boot application, you first need to include the necessary dependencies in your project's build file. Then, you can configure your application's connection to MongoDB by providing the connection details such as the host, port, and credentials. Once the connection is established, you can use Spring Data MongoDB to define entities and repositories that map to MongoDB collections and perform operations on them.

Spring Boot mongoDB requires minimal configuration and consists of four layers:

  1. Presentation layer:
    This layer deals with the MVC framework's view part, and the front end is handeled with this layer.
  2. Business layer:
    This layer deals with the MVC framework's controller part, and used for implementing business logic and validations.
  3. Persistence layer:
    This layer are used for translating business objects to database objects.
  4. Database layer:
    This layer are used for handling CRUD (Create, Read, Update, Delete) operations.

What We’re Going to Build?

We can create an imaginary grocery list for a user in our Mongodb spring boot application and perform the following actions:

  • Firstly, we define a Plain Old Java Object POJO for grocery items with attributes such as ID, name, quantity, and category within our Spring application.
  • Subsequently, we carry out create, read, update, and delete (CRUD) operations using the public interface of MongoRepository.
  • Lastly, we demonstrate an alternative method for updating documents using the MongoTemplate class.

To gain more insight into mapping POJO and MongoDB documents, refer to our article Getting Started with MongoDB and Java.

Prerequisites

Let us now begin with the setup of our spring boot mongodb project, so the prerequisites we need to setup our project are:

  • JDK:
    Install a Java Development Kit (JDK) version 8 or higher.
  • Java 1.8
  • IDE:
    Install an Integrated Development Environment (IDE), such as Eclipse, IntelliJ IDEA, or Spring Tool Suite (STS).
  • MongoDB Atlas:
    You can create your free account here.
  • Spring Initializr:
    Create a new Spring Boot project using the Spring Initializr website or from within your IDE.
  • Maven:
    you can install Maven through Eclipse using Help -> Install new software, as well.

To create a Spring boot mongodb project using Spring Initializer we will follow these steps:

  • Go to the Spring Initializr website in your web browser.
  • Fill in the following project details:
  • Project type:
    Maven or Gradle, depending on your preference, in our case, we will choose Maven.
  • Language:
    Java
  • Spring Boot version:
    choose the latest stable version
  • Group:
    com.example (or another group ID of your choice)
  • Artifact:
    myproject (or another artifact ID of your choice, in our case we will keep spring-boot-mdb)
  • Packaging:
    jar (or another packaging type of your choice)
  • Java version:
    choose the latest stable version (e.g., 17)
  • Click on the Add Dependencies button and type in Spring Web in the search box. Select the Spring Web checkbox to add the dependency.
  • Type in Spring Data MongoDB in the search box and select the Spring Data MongoDB checkbox to add the dependency.
  • Spring Web also add Apache Tomcat server, REST, and Spring MVC in our application.

spring boot project using spring initializer

After configuring the project, click on the Generate button. This will create all the necessary files to bootstrap the spring boot mongodb project, and a ZIP file will be downloaded automatically by the browser.

Once the ZIP file is downloaded, unzip the project, and open it from your IDE. You should see a project structure similar to this:

unzip project

All the dependencies we have added in our project will be mentioned inside the pom.xml file:

pom xml file

Now let us create the content in the src/main/java folder.

Implementation of MongoDB Model

To implement a MongoDB model for an imaginary grocery list for a user, we can create a Plain Old Java Object (POJO) class that represents a grocery item. This class should have fields for the item ID, name, quantity, and category. Here's an example implementation:

In this example, we have annotated the class with @Document and specified the MongoDB collection name as grocery_items. The @Id annotation specifies that the id field should be used as the document identifier.

With this model in place, we can use Spring Data MongoDB to perform CRUD operations on grocery items in our MongoDB database.

API Implementation Spring Boot MongoDB

The repository in the spring boot mongodb project is responsible for implementing the API, serving as an intermediary between the model and the database, and containing all the necessary methods for CRUD operations.

To keep all the repository files together, we create a package called com.example.springbootmdb.repository in our Mongodb and spring boot application.

Firstly, we create a public interface called ItemRepository, which extends the MongoRepository interface:

Explanation:

This code defines an interface called ItemRepository which extends the MongoRepository interface to interact with the MongoDB database. It has three methods:

  1. findItemByName(String name) -
    This method uses the @Query annotation to specify a custom query to find a GroceryItem by its name. The name parameter is passed as a query parameter using ?0.
  2. findAll(String category) -
    This method also uses the @Query annotation to specify a custom query to find all GroceryItem objects belonging to a specific category. It projects only the name and quantity fields of the documents using the fields attribute.
  3. count() -
    This method is inherited from the MongoRepository interface and simply returns the number of documents in the collection.

The interface is parameterized by the GroceryItem class, which defines the structure of the documents to be stored in the MongoDB collection, and the String class, which specifies the type of document ID. The @Query annotation is used to create custom queries to search or filter documents in the collection.

CRUD Examples: Spring Boot MongoDB

Let us now work on the creation of our Spring Boot MongoDB Application, and also run different CRUD methods to get a detailed learning.

Firstly, we will connect with our MongoDB Atlas, for the connection we can define the connection string in our application.properties file inside our src/main/resources folder. We can get the connection string from the cluster we have created in the MongoDB Atlas UI. We are not required to write any other codes related to the connection with MongoDB Atlas in any different files, as Spring Boot will manage the connection by itself.

We can also mention the database name in our Application.property file. If the database doesn't exist, then MongoDB can create the database.

In our Spring Boot MongoDB project, rather than using any View and the Controller for the UI part, we will use a CommandLineRunner to display the output on the console.

Let's create the main class SpringBootMdbApplication.java in the root package of our Spring boot mongodb application com.example.springbootmdb:

Explanation:

  • @SpringBootApplication is a Spring Boot annotation that is used to mark the main class of the application. It enables the auto-configuration and component scanning features of Spring Boot, which makes development easier and faster.
  • @EnableMongoRepositories is a Spring Data MongoDB annotation used to enable Spring Data MongoDB repositories. It is used to indicate the base package for scanning MongoDB repositories.
  • The class also implements the CommandLineRunner interface, which provides a run method to execute any code after the application context is loaded. This allows us to execute some code when the application starts.
  • @Autowired is a Spring annotation that is used to inject a dependency into a class. In this case, it injects an instance of ItemRepository into the main class.
  • The main method calls the SpringApplication.run() method to run the application. It takes two arguments: the class that contains the main method and any command-line arguments that were passed to the application.

Let us now implement CRUD operations in our project.

Create Operation

To create new documents, we can utilize the save method. This method is provided by the SimpleMongoRepository class that implements the MongoRepository interface. As our ItemRepository interface extends MongoRepository, we have access to the same method.

extend mongo repository

We will be passing a GroceryItem object as a parameter to the save method to create new documents. To save five grocery items (documents) into MongoDB, we will be using the save method.

Explanation:

  1. We created five GroceryItem objects with different properties, such as name, quantity, and category.
  2. We used the groceryItemRepo.save() method to save each GroceryItem object into the MongoDB database. This method returns the saved GroceryItem object with the generated ID value.
  3. We used System.out.println() statements to print the details of each saved GroceryItem object.

The GroceryItem objects were saved into the database using the ItemRepository interface, which extends the MongoRepository interface. The MongoRepository interface provides many built-in methods for CRUD (Create, Read, Update, Delete) operations, including the save() method. The groceryItemRepo object is an instance of the ItemRepository interface, which is autowired using the @Autowired annotation. The @SpringBootApplication annotation is used to indicate that this is a Spring Boot application, and the @EnableMongoRepositories annotation is used to enable Spring Data MongoDB repositories.

Read Operation

These are the tasks we will perform with read operations in the MongoDB Spring Boot application:

  • Fetch all documents:
    The findAll() method is used to retrieve all the documents from the MongoDB collection. It returns a list of all the grocery items present in the database.
  • Get a single document by name:
    The findItemByName() method is used to retrieve a document from the MongoDB collection based on the value of its name field. It takes a name parameter and returns a single GroceryItem object that matches the specified name.
  • Get a list of documents based on category:
    The findAll() method can also be used to retrieve a list of documents based on a specific category. The query is specified using the @Query annotation and is passed as a parameter to the method. It returns a list of GroceryItem objects that match the specified category.
  • Get the count of documents:
    The count() method is used to retrieve the count of documents present in the MongoDB collection. It returns the total number of grocery items in the database.

Explanation:

The code above contains four different methods that perform read operations on the MongoDB database using the ItemRepository interface:

  • showAllGroceryItems():
    This method fetches all the documents (grocery items) from the collection using the findAll() method and prints the details of each item to the console.
  • getGroceryItemByName(String name): This method fetches a single item (document) from the collection by its name field using the findItemByName() method and prints the details of that item to the console.
  • getItemsByCategory(String category): This method fetches a list of items based on a category from the collection using the findAll() method with a category parameter and prints the name and quantity of each item in the list to the console.
  • findCountOfGroceryItems(): This method gets the count of documents in the collection using the count() method and prints the count to the console.

We can have a method, that will return the output in a much more readable format of read operations:

Update Operation

Let us now implement the update operation in our Spring Boot MongoDB project.

Explanation:

This code shows an example of how to update documents in a MongoDB collection using Spring Boot and MongoDB. The method updateCategoryName takes a category as a parameter and changes it to a new category value called munchies.

First, it retrieves all the documents that have the given category using the findAll method of the groceryItemRepo object. It then iterates through each document and updates the category to the new category value using the setCategory method.

After all the documents have been updated, the saveAll method is called on the groceryItemRepo object to save the updated documents in the MongoDB collection. The method returns a list of the updated items, which is printed to the console to indicate the number of items that were successfully updated.

Delete operation

To delete a grocery item with a particular ID, we can use the pre-defined deleteById method available in the MongoRepository interface. Here is an example code snippet:

Explanation:

In this code, we are passing the ID of the grocery item to the deleteById method to delete it from the MongoDB database. The println statement is just to provide a confirmation message to the user that the item has been deleted.

Putting All CRUD Operations Together

Now we will implement the CommandLineRunner.run() method to call the above methods:

We have added the System.out.println statement for more readability. The output of the above code will be:

MongoTemplate in Spring Boot MongoDB: Update Operation

In addition to using the pre-defined methods provided by Spring Data MongoDB, we can also use the MongoTemplate class to perform update operations. The MongoTemplate class provides more flexibility in terms of customizing update queries.

Here's an example of how to perform an update operation using MongoTemplate:

In this example, we first create a Query object with criteria that matches the name field of the document we want to update. We then create an Update object with the new value for the quantity field.

We call the updateFirst method on the MongoTemplate object, passing in the Query, Update, and the GroceryItem class to indicate which collection to perform the update on. The updateFirst method will update the first document that matches the criteria specified in the Query.

The UpdateResult object returned by the updateFirst method contains information about the update operation, including the number of documents that were modified. We check the modifiedCount property of the UpdateResult object to determine if the update was successful.

In this example, we update the quantity of a grocery item by name, but we could also update based on other criteria such as ID or category. The MongoTemplate class provides a wide range of methods for building more complex update queries, including updating multiple documents at once.

FAQs

Here are some frequently asked questions regarding connecting Spring Boot with MongoDB:

Q: What is MongoDB?

A: MongoDB is a NoSQL document-oriented database that stores data in JSON-like documents. It is an open-source, distributed, and highly scalable database that is designed to handle big data.

Q: How to connect Spring Boot with MongoDB?

A: To connect Spring Boot with MongoDB, we can use Spring Data MongoDB, which provides a simple and powerful way to interact with MongoDB databases. We can configure Spring Data MongoDB in our Spring Boot application by adding the necessary dependencies, configuring the MongoDB connection settings, and creating MongoDB repositories.

Q: What is Spring Data MongoDB?

A: Spring Data MongoDB is a subproject of the Spring Data project that provides a simple and consistent way to interact with MongoDB databases. It provides a set of abstractions and helper classes to make it easy to work with MongoDB, such as MongoDBTemplate, MongoRepository, and MongoOperations.

Q: What is a MongoDB repository?

A: A MongoDB repository is an interface that extends the MongoRepository interface provided by Spring Data MongoDB. It defines methods for CRUD operations and other queries that can be performed on the MongoDB database. The methods defined in the repository are implemented by Spring Data MongoDB at runtime.

Q: What is the difference between MongoDBTemplate and MongoRepository?

A: MongoDBTemplate is a low-level template API provided by Spring Data MongoDB that allows us to perform CRUD operations and other queries on the MongoDB database. It provides more control and flexibility but requires more code to be written. MongoRepository is a higher-level API provided by Spring Data MongoDB that abstracts away most of the implementation details and provides a simple and consistent way to perform CRUD operations and other queries on the MongoDB database.

Q: How to perform CRUD operations with Spring Boot and MongoDB?

A: We can perform CRUD operations with Spring Boot and MongoDB using the MongoDB repositories provided by Spring Data MongoDB. We can define custom methods in the repository interface to perform specific queries on the MongoDB database, such as finding documents by a particular field, updating documents, and deleting documents.

Q: How to configure MongoDB connection settings in Spring Boot?

A: We can configure MongoDB connection settings in Spring Boot by adding the necessary properties to the application.properties or application.yml file, such as the MongoDB host, port, database name, username, and password. We can also create a MongoTemplate bean in our Spring Boot application and customize its configuration, such as setting the write concern and read preference.

Conclusion

In this article, we learned about the Connecting Spring Boot with MongoDB in java. Let us recap the points we discussed throughout the article:

  • MongoDB is a popular NoSQL database that is highly scalable and flexible, making it a good fit for many applications.
  • Spring Boot provides easy integration with MongoDB through the Spring Data MongoDB module, which provides several pre-defined operations to interact with the database.
  • The MongoTemplate class provides a more flexible way to perform database operations, allowing us to write custom queries and operations.
  • To use MongoDB with Spring Boot, we need to add the MongoDB driver and Spring Data MongoDB dependencies to our project, and configure the database connection in the application.properties file.
  • Once the database is connected, we can perform CRUD operations on our data, such as creating, reading, updating, and deleting documents.
  • We can also perform more complex queries using the MongoTemplate class, which provides methods to create custom queries, update operations, and aggregation pipelines.
  • Spring Boot provides several annotations to simplify the configuration of our MongoDB repositories, including @EnableMongoRepositories, @Document, and @Id.
  • Overall, integrating Spring Boot with MongoDB provides a powerful and flexible way to build scalable and efficient applications that can handle large amounts of data.