Getting Started

An easy way to bootstrap setting up a working environment is to create a Spring-based project via or create a Spring project in Spring Tools.

Examples Repository

The GitHub spring-data-examples repository hosts several examples that you can download and play around with to get a feel for how the library works.

Hello World

First, you need to set up a running MongoDB server. Refer to the MongoDB Quick Start guide for an explanation on how to startup a MongoDB instance. Once installed, starting MongoDB is typically a matter of running the following command: /bin/mongod

Then you can create a Person class to persist:


public class Person {

	private String id;
	private String name;
	private int age;

	public Person(String name, int age) { = name;
		this.age = age;

	public String getId() {
		return id;

	public String getName() {
		return name;

	public int getAge() {
		return age;

	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";

You also need a main application to run:

  • Imperative

  • Reactive


import static*;


import com.mongodb.client.MongoClients;

public class MongoApplication {

	public static void main(String[] args) throws Exception {

		MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "database");
		mongoOps.insert(new Person("Joe", 34));



import static*;


import com.mongodb.reactivestreams.client.MongoClients;

public class ReactiveMongoApplication {

	public static void main(String[] args) throws Exception {

		ReactiveMongoOperations mongoOps = new ReactiveMongoTemplate(MongoClients.create(), "database");

		mongoOps.insert(new Person("Joe", 34))


When you run the main program, the preceding examples produce the following output:

10:01:32,265 DEBUG - insert Document containing fields: [_class, age, name] in collection: Person
10:01:32,765 DEBUG - findOne using query: { "name" : "Joe"} in db.collection: database.Person
Person [id=4ddbba3c0be56b7e1b210166, name=Joe, age=34]
10:01:32,984 DEBUG - Dropped collection [database.person]

Even in this simple example, there are few things to notice:

  • You can instantiate the central helper class of Spring Mongo, MongoTemplate, by using the standard or reactive MongoClient object and the name of the database to use.

  • The mapper works against standard POJO objects without the need for any additional metadata (though you can optionally provide that information. See here.).

  • Conventions are used for handling the id field, converting it to be an ObjectId when stored in the database.

  • Mapping conventions can use field access. Notice that the Person class has only getters.

  • If the constructor argument names match the field names of the stored document, they are used to instantiate the object