Spring Boot MongoDB Configuration

Spring Boot MongoDB Configuration thumbnail
201K
By Dhiraj 19 January, 2020

In this quick article, we will deal with spring boot Mongo DB configuration. Spring Boot provides similar repository implementation as JPARepository for Mongo DB as well which is called MongoRepository. Hence, spring boot makes easier to access Mongo DB from a Java application.

Spring Boot Mongo DB Configuration with Properties File

There are 2 ways for spring boot Mongo DB configuration. First, we need to include spring boot artifact spring-boot-starter-data-mongodb in our pom.xml to download the required dependencies. Secondly, we define our Mongo DB connection parameters such as username, password, database in application.properties. That's all for Mongo DB configuration in Spring Boot. Now, we can start defining our interface based repository class by extending MongoRepository. Below is the example:

pom.xml
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
application.properties
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=root
spring.data.mongodb.password=root
spring.data.mongodb.database=test_db
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

Corresponding yml configuration

application.yml
spring
  data
    mongodb
      authentication-database: admin
      username: root
      password: root
      database: test_db
      port: 27017
      host: localhost
      

As long as you use Mongo 2.x, you can specify a host/port as above.

If you use the Mongo 3.0 Java driver, spring.data.mongodb.host and spring.data.mongodb.port are not supported. In such cases, spring.data.mongodb.uri should be used to provide all of the configuration.
#spring.data.mongodb.uri = mongodb://user:secret@mongo1.example.com:12345,mongo2.example.com:23456/test 
spring.data.mongodb.uri=spring.data.mongodb.uri=mongodb://root:root@localhost:27017/test_db

If you don't have above DB parameters, you can use below db.createuser()

use admin

db.createUser( { user: "root",
                 pwd: "root",
                 roles: [ { role: "readWrite", db: "db_test" }],
                   } );

OR else you can work with admin user.

db.createUser(
  {
    user: 'admin',
    pwd: 'password',
    roles: [ { role: 'root', db: 'admin' } ]
  }
);

Now, we can define our Mongo repository by extending MongoRepository as below:

DepartmentRepository.java
@Repository
public interface DepartmentRepository extends MongoRepository {

	Department findByName(String deptName);

}

Also, with the above configuration, you can directly autowire MongoTemplate to execute custom queries. We have discussed more on it in my next article here.

Spring Boot Mongo DB Java Configuration

The Java configuration requires to define two spring beans - MongoTemplate and MongoDbFactory. With MongoDbFactory, we can provide the connection parameters and later MongoTemplate uses the instance of MongoDbFactory to create it's instance. Below is the configuration:

MongoConfig.java
package com.devglan.springbootmongo.config;

import com.mongodb.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

@Configuration
public class MongoConfig {

    @Autowired
    private Environment env;

    @Bean
    public MongoDbFactory mongoDbFactory() {
        return new SimpleMongoDbFactory(new MongoClientURI(env.getProperty("spring.data.mongodb.uri")));
    }

	@Bean
	public MongoTemplate mongoTemplate() {
		MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());

		return mongoTemplate;

    }

}

Here, the uri is defined in application.properties file. As discussed above for Mongo driver version 3, spring.data.mongodb.uri should be used to provide all of the configuration.

spring.data.mongodb.uri=mongodb://root:root@localhost:27017/test_db

We already demonstrated using MongoRepository in the above example. Below is a simple example to use MongoTemplate. In the next article, we will look into different other ways to query using MongoTemplate.

Here is the next article that demonstrates the different use cases with MongoTemplate and MongoRepository.

public Department getUserById(String deptName) {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(deptName));
        return mongoTemplate.findOne(query, Department.class);
   }

Spring Boot Embedded Mongo DB Configuration

To configure embedded Mongo DB in an existing spring boot app, we only need to include below maven dependency in the pom.xml file. This will by default, connect to the test database. For a different database, we can set the spring.data.mongodb.database property in the application.properties configuration file.

<dependency>
	<groupId>de.flapdoodle.embed</groupId>
	<artifactId>de.flapdoodle.embed.mongo</artifactId>
</dependency>

The remaining Mongo DB configurations remains same as above and now we are set to use the embedded Mongo DB instance running at 27017 port.

Conclusion

In this article, we discussed different ways for spring boot MongoDB configuration. We tried configuring it using application.properties file as well as used Java config and provided some example of mongo repository implementation with the project.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.

Further Reading on Spring Boot