This guide walks you through the process of using Spring Data MongoDB to build an application that stores data in and retrieves it from MongoDB, a document-based database.

What you’ll build

You will store Person POJOs in a MongoDB database using Spring Data MongoDB.

What you’ll need

How to complete this guide

Like most Spring Getting Started guides, you can start from scratch and complete each step, or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

To start from scratch, move on to Set up the project.

To skip the basics, do the following:

When you’re finished, you can check your results against the code in gs-accessing-data-mongodb/complete.

Set up the project

First you set up a basic build script. You can use any build system you like when building apps with Spring, but the code you need to work with Gradle and Maven is included here. If you’re not familiar with either, refer to Building Java Projects with Gradle or Building Java Projects with Maven.

Create the directory structure

In a project directory of your choosing, create the following subdirectory structure; for example, with mkdir -p src/main/java/hello on *nix systems:

└── src
    └── main
        └── java
            └── hello

Create a Gradle build file

Below is the initial Gradle build file. But you can also use Maven. The pom.xml file is included right here. If you are using Spring Tool Suite (STS), you can import the guide directly.

If you look at pom.xml, you’ll find it has a specific version of maven-compiler-plugin. This is NOT recommended in general. Instead, it’s meant to solve an issue with our CI system that defaulted to a very old (pre-Java5) version of this plugin. build.gradle
buildscript {
    repositories {
        maven { url "" }
    dependencies {

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-accessing-data-mongodb'
    version =  '0.1.0'

repositories {
    maven { url "" }

dependencies {

task wrapper(type: Wrapper) {
    gradleVersion = '1.11'

Install and launch MongoDB

With your project set up, you can install and launch the MongoDB database.

If you are using a Mac with homebrew, this is as simple as:

$ brew install mongodb

With MacPorts:

$ port install mongodb

For other systems with package management, such as Redhat, Ubuntu, Debian, CentOS, and Windows, see instructions at

After you install MongoDB, launch it in a console window. This command also starts up a server process.

$ mongod

You probably won’t see much more than this:

all output going to: /usr/local/var/log/mongodb/mongo.log

Define a simple entity

MongoDB is a NoSQL document store. In this example, you store Customer objects.


package hello;


public class Customer {

    private String id;

    private String firstName;
    private String lastName;

    public Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;

    public String toString() {
        return String.format(
                "Customer[id=%s, firstName='%s', lastName='%s']",
                id, firstName, lastName);


Here you have a Customer class with three attributes, id, firstName, and lastName. The id is mostly for internal use by MongoDB. You also have a single constructor to populate the entities when creating a new instance.

In this guide, the typical getters and setters have been left out for brevity.

id fits the standard name for a MongoDB id so it doesn’t require any special annotation to tag it for Spring Data MongoDB.

The other two properties, firstName and lastName, are left unannotated. It is assumed that they’ll be mapped to columns that share the same name as the properties themselves.

The convenient toString() method will print out the details about a customer.

MongoDB stores data in collections. Spring Data MongoDB will map the class Customer into a collection called customer. If you want to change the name of the collection, you can use Spring Data MongoDB’s @Document annotation on the class.

Create simple queries

Spring Data MongoDB focuses on storing data in MongoDB. It also inherits functionality from the Spring Data Commons project, such as the ability to derive queries. Essentially, you don’t have to learn the query language of MongoDB; you can simply write a handful of methods and the queries are written for you.

To see how this works, create a repository interface that queries Customer documents.


package hello;

import java.util.List;


public interface CustomerRepository extends MongoRepository<Customer, String> {

    public Customer findByFirstName(String firstName);
    public List<Customer> findByLastName(String lastName);


CustomerRepository extends the MongoRepository interface and plugs in the type of values and id it works with: Customer and String. Out-of-the-box, this interface comes with many operations, including standard CRUD operations (create-read-update-delete).

You can define other queries as needed by simply declaring their method signature. In this case, you add findByFirstName, which essentially seeks documents of type Customer and finds the one that matches on firstName.

You also have findByLastName to find a list of people by last name.

In a typical Java application, you write a class that implements CustomerRepository and craft the queries yourself. What makes Spring Data MongoDB so useful is the fact that you don’t have to create this implementation. Spring Data MongoDB creates it on the fly when you run the application.

Let’s wire this up and see what it looks like!

Create an Application class

Here you create an Application class with all the components.


package hello;

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

public class Application implements CommandLineRunner {

	private CustomerRepository repository;

	public static void main(String[] args) {, args);

	public void run(String... args) throws Exception {


		// save a couple of customers Customer("Alice", "Smith")); Customer("Bob", "Smith"));

		// fetch all customers
		System.out.println("Customers found with findAll():");
		for (Customer customer : repository.findAll()) {

		// fetch an individual customer
		System.out.println("Customer found with findByFirstName('Alice'):");

		System.out.println("Customers found with findByLastName('Smith'):");
		for (Customer customer : repository.findByLastName("Smith")) {



In the configuration, you only need to add the usual @EnableAutoConfiguration as our repository is located in the same package; Spring Boot will handle those repositories automatically as long as they are included in the same package (or a sub-package) of your @EnableAutoConfiguration class. For more control over the registration process, you can use the @EnableMongoRepositories annotation.

Spring Data MongoDB uses the MongoTemplate to execute the queries behind your find* methods. You can use the template yourself for more complex queries, but this guide doesn’t cover that.

Application includes a main() method that autowire an instance of CustomerRepository: Spring Data MongoDB dynamically creates a proxy and injects it there. We use the CustomerRepository through a few tests. First, it saves a handful of Customer objects, demonstrating the save() method and setting up some data to work with. Next, it calls findAll() to fetch all Customer objects from the database. Then it calls findByFirstName() to fetch a single Customer by her first name. Finally, it calls findByLastName() to find all customers whose last name is "Smith".

Build an executable JAR

You can build a single executable JAR file that contains all the necessary dependencies, classes, and resources. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

./gradlew build

Then you can run the JAR file:

java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar

If you are using Maven, you can run the application using mvn spring-boot:run. Or you can build the JAR file with mvn clean package and run the JAR by typing:

java -jar target/gs-accessing-data-mongodb-0.1.0.jar
The procedure above will create a runnable JAR. You can also opt to build a classic WAR file instead.

Run the service

If you are using Gradle, you can run your service at the command line this way:

./gradlew clean build && java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar
If you are using Maven, you can run your service by typing mvn clean package && java -jar target/gs-accessing-data-mongodb-0.1.0.jar.

You can alternatively run the app directly from Gradle like this:

./gradlew bootRun
With mvn, you can run mvn spring-boot:run.

As our Application implements CommandLineRunner, the run method is invoked automatically when boot starts. You should see something like this (with other stuff like queries as well):

== Customers found with findAll():
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
Customer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']

== Customer found with findByFirstName('Alice'):
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
== Customers found with findByLastName('Smith'):
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
Customer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']


Congratulations! You set up a MongoDB server and wrote a simple application that uses Spring Data MongoDB to save objects to and fetch them from a database — all without writing a concrete repository implementation.

If you’re interesting in exposing MongoDB repositories with a hypermedia-based RESTful front end with little effort, you might want to read Accessing MongoDB Data with REST.