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 Will build
You will store Customer POJOs (Plain Old Java Objects) in a MongoDB database by using Spring Data MongoDB.
What You Need
- About 15 minutes
- A favorite text editor or IDE
- JDK 1.8 or later
- Gradle 4+ or Maven 3.2+
- You can also import the code straight into your IDE:
- Spring Tool Suite (STS)
- IntelliJ IDEA
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. Learn more from MongoDB Training
To start from scratch, move on to Starting with Spring Initializr.
To skip the basics, do the following:
- Download and unzip the source repository for this guide, or clone it using Git:
git clone https://github.com/spring-guides/gs-accessing-data-mongodb.git - cd into
gs-accessing-data-mongodb/initial - Jump ahead to Install and Launch MongoDB.
When you finish, you can check your results against the code in gs-accessing-data-mongodb/complete.
Starting with Spring Initializr
For all Spring applications, you should start with the Spring Initializr. The Initializr offers a fast way to pull in all the dependencies you need for an application and does a lot of the set up for you. This example needs only the Spring Data MongoDB dependency. The following image shows the Initializr set up for this sample project:
The following listing shows the pom.xml file created when you choose Maven:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<parent> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <groupId>com.example</groupId>
<artifactId>accessing-data-mongodb</artifactId>
<version>0.0.1-SNAPSHOT</version> <name>accessing-data-mongodb</name>
<description>Demo project for Spring Boot</description>
<properties> <java.version>1.8</java.version> </properties>
<dependencies> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions> <exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion> </exclusions>
</dependency> </dependencies>
<build> <plugins> <plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The following listing shows the build.gradle file created when you choose Gradle:
plugins { id 'org.springframework.boot' version '2.2.0.RELEASE' id 'io.spring.dependency-management' version '1.0.8.RELEASE' id 'java' }
group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '1.8' repositories { mavenCentral() }
dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-mongodb' testImplementation('org.springframework.boot:spring-boot-starter-test')
{ exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' } }
test { useJUnitPlatform() }
Install and Launch MongoDB
With your project set up, you can install and launch the MongoDB database.
If you use a Mac with Homebrew, you can run the following command:
$ brew install mongodb
With MacPorts, you can run the following command: For more info MongoDB Certification
$ port install mongodb
For other systems with package management, such as Redhat, Ubuntu, Debian, CentOS, and Windows.
After you install MongoDB, you can launch it in a console window by running the following command (which also starts up a server process):
$ mongod
You should see output similar to the following:
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. The following listing shows the Customer class (in src/main/java/com/example/accessingdatamongodb/Customer.java):
package com.example.accessingdatamongodb;
import org.springframework.data.annotation.Id;
public class Customer { @Id public String id;
public String firstName; public String lastName;
public Customer() {}
public Customer(String firstName, String lastName)
{ this.firstName = firstName; this.lastName = lastName; }
@Override 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.
id fits the standard name for a MongoDB ID, so it does not 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 are mapped to fields that share the same name as the properties themselves. Get More programming skills from MongoDB Certification
The convenient toString() method prints out the details about a customer.
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 need not learn the query language of MongoDB. You can 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, as the following listing (in src/main/java/com/example/accessingdatamongodb/CustomerRepository.java) shows:
package com.example.accessingdatamongodb;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
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 that it works with: Customer and String, respectively. This interface comes with many operations, including standard CRUD operations (create, read, update, and delete).
You can define other queries by declaring their method signatures. In this case, add findByFirstName, which essentially seeks documents of type Customer and finds the documents that match on firstName.
You also have findByLastName, which finds 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 need not create this implementation. Spring Data MongoDB creates it on the fly when you run the application.
Now you can wire up this application and see what it looks like!
Create an Application Class
Spring Initializr creates a simple class for the application. The following listing shows the class that Initializr created for this example (in src/main/java/com/example/accessingdatamongodb/AccessingDataMongodbApplication.java):
package com.example.accessingdatamongodb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public class AccessingDataMongodbApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataMongodbApplication.class, args); } }
@SpringBootApplication is a convenience annotation that adds all of the following:
@Configuration: Tags the class as a source of bean definitions for the application context.@EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, ifspring-webmvcis on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up aDispatcherServlet.@ComponentScan: Tells Spring to look for other components, configurations, and services in thecom/examplepackage, letting it find the controllers.
The main() method uses Spring Boot’s SpringApplication.run() method to launch an application.
Did you notice that there was not a single line of XML? There is no web.xml file, either. This web application is 100% pure Java and you did not have to deal with configuring any plumbing or infrastructure.
Spring Boot automatically handles those repositories as long as they are included in the same package (or a sub-package) of your @SpringBootApplication 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 does not cover that.
Now you need to modify the simple class that the Initializr created for you. You need to set up some data and use it to generate output. The following listing shows the finished AccessingDataMongodbApplication class (in src/main/java/com/example/accessingdatamongodb/AccessingDataMongodbApplication.java):
package com.example.accessingdatamongodb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public class AccessingDataMongodbApplication implements CommandLineRunner { @Autowired private CustomerRepository repository;
public static void main(String[] args) {
SpringApplication.run(AccessingDataMongodbApplication.class, args); }
@Override public void run(String... args)
throws Exception { repository.deleteAll();
// save a couple of customers repository.save(new Customer("Alice", "Smith"));
repository.save(new Customer("Bob", "Smith"));
// fetch all customers
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : repository.findAll()) {
System.out.println(customer); }
System.out.println();
// fetch an individual customer
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------"); System.out.println(repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : repository.findByLastName("Smith")) {
System.out.println(customer); } } }
AccessingDataMongodbApplication includes a main() method that autowires 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 use. 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 run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar so makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
If you use Gradle, you can run the application by using ./gradlew bootRun. Alternatively, you can build the JAR file by using ./gradlew build and then run the JAR file, as follows:
java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar
If you use Maven, you can run the application by using ./mvnw spring-boot:run. Alternatively, you can build the JAR file with ./mvnw clean package and then run the JAR file, as follows:
java -jar target/gs-accessing-data-mongodb-0.1.0.jar
To get in-depth knowledge, enroll for a live free demo on MongoDB Online Training