Spring Boot MongoDB Configuration

author-image   By Dhiraj,   03 July, 2019 7K

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.

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

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.

If You Appreciate This, You Can Consider:

  • Like us at: Facebook or follow us at Twitter
  • Share this article on social media or with your teammates.
  • We are thankful for your never ending support.

About The Author

author-image

I am an energetic professional who enjoys the challenges involved in working with people and resolving real-time problems. Technical expertise in building highly scalable, distributed and self-healing cloud applications. Technical Skills: Java/J2EE, Spring Framework, Hibernate, Angular, Reactive Programming, Microservices, Rest APIs, Kafka, ELK, etc.

Further Reading on Spring Boot

1 Spring Data Mongodb Queries

2 Spring Boot Mongodb Crud

3 Spring Boot Redis Cache

4 Spring Boot Angular Captcha

5 Spring Boot Async Task Executor

6 Spring Boot Jpa Hibernate Login Example

7 Spring Ehcache Cacheable Example Javaconfig

8 Spring Jms Activemq Integration Example