In this post, we will configure a Spring boot application to use a MongoDB persistence back-end.

If you enjoy listening to music while working, or if you have annoying coworkers who prefer to have their coffee discussions right at your desk, then we recommend that you check out the Sony Wireless Noise Cancelling Headphones WH1000XM3 (click to check on Amazon). These headphones come with a built in microphone, active noise cancelling, superior sound quality, and a built in Alexa all packaged by Sony’s legendary build quality.


MongoDB is NoSQL, cross-platform, document based database engine. It was initially release in 2009 but has been increasingly popular over the years thanks to its scaleability and increased popularity of NoSQL database systems.

Unlike traditional relational database systems such as Postgres and Oracle, MongoDB like other NoSQL systems does not have relationships among entities. MongoDB uses documents and embedded/nested documents to map a “relationship” between two entities. Each document is written in JSON format, and a database “table”, for example, “users” is a collection of documents.

Combining the power of MongoDB and Spring-Data along with the ease of development of Spring boot provides a really powerful development stack. So let us get started up by defining the dependencies in our POM file.

In our example, we will be using Spring boot 2.1.4, MongoDB 4.0.8 and JDK 8.

Adding the required dependencies

In order to make use of MongoDB within a Spring boot application, you will need two dependencies. First is the spring-data dependency which provides us the data management API from Spring, and the second is spring-boot-starter-data-mongodb which is needed to include the MongoDB driver and other MongoDB support libraries. Since our module will use the spring-boot-starter-parent, we only need to explicit add the spring-boot-starter-data-mongodb. The starter parent should take care of spring-data. Our POM xml will look as follows.

Configuring connectivity and authentication to the MongoDB server

The next step is to make sure our application can find the MongoDB server and connect to it with the correct user on the correct database. For this, we will need to configure the connection properties in the file. There are two methods to configuring the connectivity. First is to define each connection property such as the username, password, host, etc.. separately. This can be done as follows:

The second option is to build a connection URI.

Please note that if you are logging in with a database superuser inside the Mongo admin database, then you will need to define the authentication-database property.

If your user was created directly on the required database, then the authentication-database property is not necessary.

Creating an entity model

The nice thing about MongoDB is that it is a document based engine. Therefore, when creating a new entity model on the application side, there are no schema changes required on the database side. You can simply create a new entity model or modify an existing one and get on with it.

So let us start by creating our entity class. Our entity will be a “Car”, with only a few fields as follows:

Notice that the only annotation required here is the @Id annotation, which tells spring data where to populate the id field that is generated from the database engine.

Creating a MongoDB CRUD Repository

In order to be able to perform read/write operations on our Car entity, we will need to create a repository for it. The spring-data-mongodb library provides us with a MongoRepository that allows us to perform CRUD operations such as findAll, save or delete.

Let us define our “CarRepository” along with two search methods. The first will search for cars with a specific model. The second will search for cars with a horse power value that is less than the search parameter. In order to do this, we will need to create the CarRepository as an interface and extend the MongoRepository interface.

Notice that for the first search method, all we need to do is to name the method and the search parameter with the actual required search parameter and spring-data takes care of the rest of the implementation.

Our second search function is a bit more interesting so let us break it down.

  • @Query: This annotation exists in both spring-data and spring-data-mongodb. It indicates that the following function should perform the given query. In the case of MongoDB, we provide the query in the MongoDB query format, which is basically a JSON document.
  • ‘horsePower’ : This is the name of the search parameter that we will use to search among the documents.
  • $lt : This is short for “less than”. If we wanted to search for cars with a horse power value greater than our parameter, then we can use $gt .

Activating MongoDB repositories using @EnableMongoRepositories

In order for Spring to find our MongoDB repository, we need to indicate to Spring where they are located. We can do this by using the annotation @EnableMongoRepositories. If this is not done, then Spring boot will try to find your repositories by scanning packages and subpackages that exist in your application main class (the one with the @SpringBootApplication configuration).

It may be wise to explicitly state the repositories location as this is less error prone and also gives your code reader an idea of where to find your repositories. For this, we create a Java configuration class, with the annotation configured as follows.

Notice that we scan the package and subpackages of “com.nullbeans.persistence.repositories”. You can also add the annotation without stating any base packages. In that case, Spring will detect the package of the class that has the @EnableMongoRepositories annotation , in this case “com.nullbeans.persistence.config” and try to scan that package and its sub directories. Please find the current package structure if things are starting to get confusing:

Testing our application

Now, let us put it all together by creating a simple Spring boot application in order to test the connectivity to the database. For this, we will create a simple subclass of Spring-boot’s command line runner.

Let us go through the run method step by step:

  • carRepository.deleteAll() : This method comes from Spring-data. It allows us to delete all items in the given database table or in the case of MongoDB, the collection.
  • This method will try to persist the object into the database.
  • carRepository.findByModel(“488”): Here we call our custom method to search for cars with the model name “488”
  • carRepository.findCarsWithHorsePowerLessThan(200): Here we call our 2nd custom method to search for cars with a horsePower value of less than 200.

If we run our program, we will get the following result:

If we take a look at the MongoDB database, we will find the following the spring boot application created a collection called “car” in the “nullbeans” database. The collection has the following documents.


In this tutorial, we have created a simple Spring boot application that interacts with a MongoDB. We have configured the application to connect and authenticate to the database by configuring the connection URI and by configuring individual connectivity parameters. We then proceeded to create an entity model and its corresponding repository. We then discussed the @EnableMongoRepositories annotation and we tested our application by creating and searching for data documents in our example entity / collection.

If you want to improve your Spring boot skills, then I would suggest that you check out the book “Learning Spring Boot 2.0 – Second Edition: Simplify the development of lightning fast applications based on microservices and reactive programming”(click to check current price on Amazon) by Greg Turnquist. The book covers Spring boot basics and provides an overview of integrating important technologies such as AMQP messaging and REST into your application.

If you liked this tutorial then please make sure to subscribe to our twitter feed by clicking the follow button below 😉