Springboot MongoDB Repository – Code Example


This blog represents code required to create a Spring boot application that uses Spring Data MongoRepository interface to connect with MongoDB database.

Step 1: Create a Springboot Maven project

Create a new Spring Starter Project using Eclipse IDE. This would create a class annotated with @SpringBootAnnotation.

Step 2: Include Spring Data Mongo support in pom.xml


Step 3: Configure Mongoclient for database connectivity

Create a Configuration class which is used to instantiate a MongoClient for connecting with MongoDB database.

package com.vflux.demo.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

@EnableMongoRepositories(basePackages = "com.vflux.demo.repository")
public class MongoConfig extends AbstractMongoConfiguration {

    private String  dbName;

    private String  authDB;

    private String  host;

    private String port;

    private String  username;

    private String  password;

    protected String getDatabaseName() {
        return this.dbName;

    public Mongo mongo() throws Exception {                
        List<ServerAddress> seeds = new ArrayList<ServerAddress>();
        seeds.add( new ServerAddress(this.host, Integer.parseInt(this.port.trim())) );
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        MongoCredential userCredential = MongoCredential.createCredential(this.username, this.authDB, this.password.toCharArray());
        return new MongoClient( seeds, credentials );

    protected String getMappingBasePackage() {
        return "com.vflux.demo";


Step 3: Define MongoDB details in application.properties

# MongoDB properties

Step 4: Invoke MongoRepository instance

Place following code in SpringBootAnnotation class for invoking MongoRepository instance (UserDAO in the code given below). In ideal scenario, you would want to invoke this DAO class from a service class.

package com.vflux.demo;

import java.util.concurrent.ThreadLocalRandom;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.vflux.demo.domain.User;
import com.vflux.demo.repository.UserDAO;

public class DemoAppApplication {

    private static UserDAO userDAO;

    public void setPersonCountDAO(UserDAO userDAO) {
        this.userDAO = userDAO;

    public static void main(String[] args) {
        SpringApplication.run(DemoAppApplication.class, args);

    private static void createUser() {
        User user = new User();


Step 5: Create a UserDAO interface

package com.vflux.demo.repository;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.vflux.demo.domain.User;

public interface UserDAO extends MongoRepository<User, String> {
    User insert(User user);

Step 6: Create a Document class

In the above code, a User class is used. The User class can represent a collection in MongoDB with name as user.

package com.vflux.demo.domain;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

public class User {

    private String id;
    private String firstname;
    private String middlename;
    private String lastname;
    private int age;
    private String location;
    private String role;

    public User() {}

    public String getFirstname() {
        return firstname;

    public void setFirstname(String firstname) {
        this.firstname = firstname;

    public String getMiddlename() {
        return middlename;

    public void setMiddlename(String middlename) {
        this.middlename = middlename;

    public String getLastname() {
        return lastname;

    public void setLastname(String lastname) {
        this.lastname = lastname;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public String getLocation() {
        return location;

    public void setLocation(String location) {
        this.location = location;

    public String getRole() {
        return role;

    public void setRole(String role) {
        this.role = role;
Ajitesh Kumar

Ajitesh Kumar

Ajitesh is passionate about various different technologies including programming languages such as Java/JEE, Javascript, PHP, .NET, C/C++, mobile programming languages etc and, computing fundamentals such as application security, cloud computing, API, mobile apps, google glass, big data etc.Recently, he has been digging deep into the field of data science and machine learning.

Follow him on Twitter and Google+.
Ajitesh Kumar

Leave A Reply

Time limit is exhausted. Please reload the CAPTCHA.