Getting Started

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

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: ${MONGO_HOME}/bin/mongod

To create a Spring project in STS:

  1. Go to File → New → Spring Template Project → Simple Spring Utility Project, and press Yes when prompted. Then enter a project and a package name, such as org.spring.mongodb.example. .Add the following to the pom.xml files dependencies element:

    <dependencies>
    
      <!-- other dependency elements omitted -->
    
      <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>2.1.4.RELEASE</version>
      </dependency>
    
    </dependencies>
  2. Change the version of Spring in the pom.xml to be

    <spring.framework.version>5.1.4.RELEASE</spring.framework.version>
  3. Add the following location of the Spring Milestone repository for Maven to your pom.xml such that it is at the same level of your <dependencies/> element:

    <repositories>
      <repository>
        <id>spring-milestone</id>
        <name>Spring Maven MILESTONE Repository</name>
        <url>http://repo.spring.io/libs-milestone</url>
      </repository>
    </repositories>

The repository is also browseable here.

You may also want to set the logging level to DEBUG to see some additional information. To do so, edit the log4j.properties file to have the following content:

log4j.category.org.springframework.data.mongodb=DEBUG
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %40.40c:%4L - %m%n

Then you can create a Person class to persist:

package org.spring.mongodb.example;

public class Person {

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

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

  public String getId() {
    return id;
  }
  public String getName() {
    return name;
  }
  public int getAge() {
    return age;
  }

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

You also need a main application to run:

package org.spring.mongodb.example;

import static org.springframework.data.mongodb.core.query.Criteria.where;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

import com.mongodb.MongoClient;

public class MongoApp {

  private static final Log log = LogFactory.getLog(MongoApp.class);

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

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

    log.info(mongoOps.findOne(new Query(where("name").is("Joe")), Person.class));

    mongoOps.dropCollection("person");
  }
}

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

10:01:32,062 DEBUG apping.MongoPersistentEntityIndexCreator:  80 - Analyzing class class org.spring.example.Person for index information.
10:01:32,265 DEBUG ramework.data.mongodb.core.MongoTemplate: 631 - insert Document containing fields: [_class, age, name] in collection: Person
10:01:32,765 DEBUG ramework.data.mongodb.core.MongoTemplate:1243 - findOne using query: { "name" : "Joe"} in db.collection: database.Person
10:01:32,953  INFO      org.spring.mongodb.example.MongoApp:  25 - Person [id=4ddbba3c0be56b7e1b210166, name=Joe, age=34]
10:01:32,984 DEBUG ramework.data.mongodb.core.MongoTemplate: 375 - 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 com.mongodb.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