Spring Boot MongoDB With Examples

Welcome to Spring Boot MongoDB example. Spring Boot is the easiest way to spin a spring project quickly and MongoDB is the most popular NoSQL database. Let’s see how to integrate spring with MongoDB database.

Spring Boot MongoDB

We need following APIs to work with Spring Boot and MongoDB database.

  • Spring Data MongoDB
  • Spring Boot

There are two approaches through which we can connect to MongoDB database – MongoRepository and MongoTemplate. We will try to establish what one API offers over another and when should you choose any one of them for your use-case. We will make use of Spring Initializr tool for quickly setting up the project. So, let’s get started.

Spring Boot MongoDB Project Setup

We will make use of Spring Initializr tool for quickly setting up the project. We will use just two dependencies as shown below:

spring-initializr-2

Download the project and unzip it. Then import it into your favorite IDE – Eclipse or IntelliJ IDEA.

Maven Dependencies

Though we already completed the setup with the tool, if you want to set it up manually, we use Maven build system for this project and here are the dependencies we used:

Make sure to use stable version for Spring Boot from the maven central.

Spring Boot MongoDB Model Class

We have a simple model class User.java.

Spring Boot MongoDB APIs

We will have following functionalities and Database interactions in our app.

  • Get all users
  • Get a user with ID
  • Get user settings
  • Get a particular key from the Map
  • Add/Update user setting

Spring Data MongoDB – MongoRepository

Now we will use Spring Data MongoDB repository to access our data. Spring Data MongoRepository provide us common functionalities that we can easily plug-in and use it.

Let us define our Repository interface.

Defining MongoDB properties

Before we lay out our controller, it is important that we make a connection with a local instance of MongoDB. We will use Spring Boot properties to do this.

So, the app will run on port 8102 and connect to a local mongoDB instance with provided credentials. If you have a local instance without authorization enabled, you can just remove the first three lines of configuration.

Defining the Spring Controller

Let us finally move to making our Controller class.

We just Autowired the repository interface dependency and we will use this next.

Defining the APIs

For the functionalities we mentioned, we will now be making APIs and accessing the userRepository dependency which will internally use Spring Data MongoRepository API. Notice that we do not have to write any database interaction code in the interface as Spring Data does it all for us.

Getting all users

findAll() is just a method which Spring Data MongoRepository provides internally.

Getting a user by ID

Now, let us get a specific user with an ID.

findOne() is just a method which Spring Data MongoRepository provides internally to get an Object by an ID.

Adding a new User

We will be adding a new user in the function below.

Getting User settings

Now that we have added sample data into the DB, let’s try to extract some part of it.

Getting a particular User setting

Notice in the above query, we got the user object, then extracted the complete Setting map (which could have contained 1000s of objects) and finally got our own value. This is a downside for Spring Data query when we use it as straight API.

Adding a new User setting

Let’s try to add some data to an existing user:

With all the code we wrote, it’s clear that we didn’t have to write a single line of code to access the database apart from defining the repository interface and autowiring the dependency.

This is the ease Spring Data MongoRepository API offers us but it also has some downsides. We will elaborate this when we have defined the MongoTemplate version as well. Let’s get started with that too.

Spring Data MongoDB – MongoTemplate

We will be defining the MongoTemplate database queries here. With MongoTemplate, you will see that we have much more granular control over what we query and what data is included in the results.

Defining the DAL interface

To provide a contract at the database access layer, we will start by defining an interface which works just like our Spring Data in-built methods.

Implementing the DAL interface

Let’s move on and define these methods.

The method implementations in above class are using MongoTemplate dependency.

See how getUserById(...) method gets the user. We construct a query and passed required parameters.

What will interests you more is the getUserSetting query. Let us understand what happened above:

  • We constructed queries with criteria to check equality.
  • The include method includes the field names which the result should include when it is extracted from DB. This means, in this case, userSettings key will be extracted which will save a lot of data to be fetched which is not needed
  • Also, we queried upon both user and the map key. Id any of it isn’t found, we return empty data meaning the required key wasn’t found. This saves from even fetching the User object at all if the required key was not present

Spring Data MongoDB Test Run

We can run this app simply by using a single command:

Once the app is running, we can try saving a new user by using this API:

As this will be a POST request, we will be sending JSON data as well:

As we are returning the Mongo response itself, we will get something like:

Spring Data MongoDB MongoRepository Example Create

You can get all users by using the API as GET request:

We will get back something like:

Spring Data MongoDB

If you see above UserController class, we haven’t hooked up MongoTemplate to be used. Below code snippet shows the changes required to use MongoTemplate for reading user settings.

Restart the app and run scenarios to get all user settings and to get any specific key. Below image shows the output from Postman app.

Spring-Data-MongoDB-MongoTemplate-Example

 

Spring-Data-MongoDB-MongoTemplate-Example

MongoTemplate vs MongoRepository

  • MongoTemplate provides a lot more control when it comes to querying data and what data to pull from database.
  • Spring Data repositories provide us a convenient outlook on how to fetch data.
  • MongoTemplate is database dependent. What this means is, with Spring Data repositories, you can easily switch to a different database altogether by simply using a different Spring Data repositories for MySQL or Neo4J or anything else. This is not possible with MongoTemplate.

Spring Boot MongoDB Summary

In this lesson, we looked at how MongoTemplate can provide us more control over Spring Data repositories but can also be a little complicated when deeper queries are involved. So, this is completely your call what to choose when you develop your idea. Feel free to leave comments below.

Download the source code from below link. Please make sure that you change the MongoDB credentials before running the provided app.

By admin

Leave a Reply

%d bloggers like this: