Using Spring Data MongoDB

Spring Data MongoDB provides a great third party support based on standard MongoDB Java Driver.


Following dependencies are required. Check for latest version via Nexus Central Repository:

  1. spring-data-mongodb
  2. mongo-java-driver

Setup Mongo Connection, Template and Repository Scanning

This is similar idea with setting up db datasource. In this example the mongo database server is located at localhost:27017 (default). The MongoDB database name used is enrollment. The <mongo:repositories ...> tag specifies the base package to scan for repository classes

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="" xmlns:xsi=""

  <mongo:mongo host="localhost" port="27017" />

  <bean id="mongoTemplate" class="">
    <constructor-arg ref="mongo" />
    <constructor-arg value="enrollment" />
  <mongo:repositories base-package="com.gerrydevstory.enrollment"/>

Domain / Entity Class

Example on this post will be based on a simple Student entity class with only id and name field:


public class Student {
  @Id private String id;
  private String name;
  // getters & setters..

Without explicit configuration this entity class will be mapped into MongoDB collection name student. To override this default behavior use @Document(collection = "...") annotation.

Repository Class

Simply add an interface extending Spring Data Repository interface. Below sample uses PagingAndSortingRepository, which extends CrudRepository which provides most basic operation. The type parameter specifies this repository operates over Student entity, with the ID type being String. Spring Data will automatically generate an implementation of this interface.

public interface StudentRepository extends PagingAndSortingRepository<Student, String> {


This repository can now be injected into controllers:

public class StudentController {

  @Autowired private StudentRepository studentRepository;

  @RequestMapping(method = GET)
  public String get(Model model) {
    Iterable<Student> students = studentRepository.findAll();
    return "student";

  @RequestMapping(value = "/new", method = POST)
  public String addNew(@ModelAttribute("student") Student student) {;


Read More

Learn more about Spring Data and MongoDB:


One thought on “Using Spring Data MongoDB

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s