Getting Started with SpringBoot and MongoDB

How to Use MongoDB with Spring Boot

Hamza Sabljakovic
Enlear Academy

--

Starting with Spring Boot and MongoDB can be overwhelming due to the multiple options available (Mongo templates, Spring data repositories, QueryDSL). This post will focus on the Spring Data Mongo repositories module, giving developer experience similar to working with Spring and relational databases. Besides, we will heavily rely on Spring Boot powerful defaults and avoid unnecessary boilerplate, configurations, beans, etc. As the purpose of this tutorial is to get you started with a minimal setup and as little overhead as possible, many best practices will be omitted.

We will begin at the place where many Spring projects start, at the start.spring.io. Here we will pick only the dependency that is necessary to set up mongo.

MongoDB dependencies in a spring boot project

You can download the same setup from this link. Now that we have all the dependencies, the next step is to create a class representing the document that we want to store in MongoDB. In this tutorial, we will use an example of a product.

Mongo document example

If you have experience with Spring Data and relation databases, the following code will look very familiar. To get the CRUD data access functionality, we have to create a repository interface that extends the MongoRepository and gives it the product document class and the type of the id (in our case, String).

Mongo repository example

We will get several CRUD methods out of the box by defining the interface (not implementing it!). We won’t go into how this works under the hood in this post, but you can read more here.

Methods available by just extending the MongoRepository interface

And here is the link to the interface definition in the Spring Data MongoDB GitHub repository.

Now, if you have MongoDB running locally on port 20217, no further configuration is required. By default, on the application start, the spring application will try to connect to the localhost:20217. Also, by default, collections will be created in the database named test .

Logs when the Spring application is started

However, if the mongo is running on a different port or machine, that can be easily adjusted by setting the connection string in the application.properties file. The property you need to set is spring.data.mongodb.uriHere you can read more and how to set the connection string via an environment variable.

As shown above, with only one class and a single interface, we got a fully functional CRUD database access layer. To get a full picture of how it all works, we will add a simple command-line runner that will use the product repository.

And if we look at database contents, for which I’m using a GUI application called NoSQL booster, you should be able to see a database test and collection product .

NoSQL booster UI

Beyond out of the box CRUD

While the built-in repositories methods are great, almost any software project will need a bit of a custom data access logic. Here again, we are presented with a choice between two options. We will cover both of them quickly.

Option #1 — using method name to define a query

If you are familiar with spring data JPA, you will feel right at home here. All we have to do is write a med and name, arguments, and return type according to the specification, and spring data will generate Query in the background. This approach will be sufficient for many simple queries, and it’s an excellent way to get started with mongo and spring as it doesn’t require learning mongo query language.

findByName(String name);

Option #2 — using Query annotation

In some other cases, using the Query annotation might be a better fit. This, however, does require knowledge of Mongo query language. To get the same result as with the previous option, we need the following annotation.

@Query("{ 'name' : ?0 }")
List<Product> findAllProductWithASpecificName(String name);

The full source code can be found on GitHub.

--

--