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

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking. Check out my other blog, Revive-n-Thrive.com
Posted in Java, MongoDB, NoSQL. Tagged with , , .

Leave a Reply

Your email address will not be published. Required fields are marked *