Spring Data MongoDB Tutorial

Spring Data for MongoDB is part of the umbrella Spring Data project which aims to provide a familiar and consistent Spring-based programming model for new data stores while retaining store-specific features and capabilities.

The Spring Data MongoDB project provides integration with the MongoDB document database. Key functional areas of Spring Data MongoDB are a POJO centric model for interacting with a MongoDB DBCollection and easily writing a Repository style data access layer.

Spring Data provides a various methodologies when it comes integrating with the MongoDB, beyond using the MongoDB Template that’s supported by Spring, a Spring-Based repository concept is also used.

Regardless of the methodology that’s being used for integrating with the MongoDB, all of those aspects that you may looking for starting from easy configurable framework reaching into an efficient and productive using of those provided libraries are exist.

Here, you will find a proper explanation of integrating Spring Data with MongoDB by using Mongo Template or by using Spring Data repositories.

Business Domain & Mapping Annotations

Spring Data provides the developer a set of annotations that could be used for mapping the Business Domain classes into MongoDB collections. MongoDB organized its data through documents; those documents are organized in collections, which are arbitrary containers for a set of documents.  Usually, you will keep documents of the same type inside a single collection, where type essentially means “similarly structured”.

For setting up MongoDB follow this link, whereas the below bullet points shows you the annotations that might be used for mapping the business domain into MongoDB collections.

  • @Id – applied at the field level to mark the field used for identiy purpose.
  • @Document – applied at the class level to indicate this class is a candidate for mapping to the database. You can specify the name of the collection where the database will be stored.
  • @DBRef – applied at the field to indicate it is to be stored using a com.mongodb.DBRef.
  • @Indexed – applied at the field level to describe how to index the field.
  • @CompoundIndex – applied at the type level to declare Compound Indexes
  • @GeoSpatialIndexed – applied at the field level to describe how to geoindex the field.
  • @Transient – by default all private fields are mapped to the document, this annotation excludes the field where it is applied from being stored in the database
  • @PersistenceConstructor – marks a given constructor – even a package protected one – to use when instantiating the object from the database. Constructor arguments are mapped by name to the key values in the retrieved DBObject.
  • @Value – this annotation is part of the Spring Framework. Within the mapping framework it can be applied to constructor arguments. This lets you use a Spring Expression Language statement to transform a key’s value retrieved in the database before it is used to construct a domain object. In order to reference a property of a given document one has to use expressions like: @Value(“#root.myProperty”) where root refers to the root of the given document.
  • @Field – applied at the field level and described the name of the field as it will be represented in the MongoDB BSON document thus allowing the name to be different than the fieldname of the class.

This isn’t a proper location for discussing the all annotations provided for achieving the mapping operation, so that not all of those mentioned annotations are being used, moreover, even some annotations that considered mandatory such as @Id when EclipseLink – JPA/NoSQL is used, when it comes to use Spring Data they are not. So let’s focus on the business domain rather annotations used for one reason and it’s being the Spring Data have been doing internal mapping without any developer involvement.


package net.javabeat.springdata.jpa.data;

import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

public class User {
	private String id;
	private String userId;
	private String fullName;
	private String age;
	private String status;
	private Address address;

	public String getUserId() {
		return userId;
	public void setUserId(String userId) {
		this.userId = userId;

	public String getFullName() {
		return fullName;
	public void setFullName(String fullName) {
		this.fullName = fullName;
	public String getAge() {
		return age;
	public void setAge(String age) {
		this.age = age;
	public String getStatus() {
		return status;
	public void setStatus(String status) {
		this.status = status;
	public String getId() {
		return id;
	public void setId(String id) {
		this.id = id;
	public Address getAddress() {
		return address;
	public void setAddress(Address address) {
		this.address = address;


package net.javabeat.springdata.jpa.data;

import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

public class Address {
	private String addressId = "";
	private String addressValue = "";

	public String getAddressId() {
		return addressId;
	public void setAddressId(String addressId) {
		this.addressId = addressId;
	public String getAddressValue() {
		return addressValue;
	public void setAddressValue(String addressValue) {
		this.addressValue = addressValue;

Setting Up Spring Data Configuration

Either you are using Spring Data for connecting your MongoDB or MongoTemplate for doing that, you have to provide your Spring Context with the required Objects.

MongoTemplate is the central class of the Spring’s MongoDB support providing a rich feature set to interact with the database. The template offers a convenience operations to create, update, delete and query for MongoDB documents and provides a mapping between your domain objects and MongoDB documents.

The mapping between Mongo documents and domain classes is done by delegating to an implementation of the interface MongoConverter that can be customized slightly. Spring provides two implementations, SimpleMappingConverter and MongoMappingConverter, but you can also create your own converter.

For instantiating a mongoTemplate you can use either JavaConfig or XML based configuration.

	<!-- Register Mongo Instance -->
	<mongo:mongo id="mongo" host="" port="27017" />
	<!--  for defining mongo template -->
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg ref="mongo" />
		<constructor-arg name="databaseName" value="JavaBeat" />

By providing these mentioned lines, you have the ability to locate mongoTemplate bean from the Spring Context that already initialized.

Once, you’ve acquired mongoTemplate, you have the ability of doing all operations that you want and as you would be seeing later.

At the other side, Spring Data points out the specialties of repository support for MongoDB. This builds on the core repository support that you’ve used before at the Spring Data – JPA. To use the repository concept you have to define your repository and attach the required XML element inside Spring Context XML file. Mongo namespace provides you an XML element for defining the proper repository for being used later on.

	<!-- For defining mongo repository -->
	<mongo:repositories base-package="net.javabeat.springdata.repo" />

And use @Autowired for injecting allowing Spring Data injecting the created proxy into your Bean service. Look below at the Repository and Spring Bean Injecting.


package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.User;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

public interface UserRepository extends CrudRepository<User, String>{}


package net.javabeat.springdata.beans;

import net.javabeat.springdata.repo.UserRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class RegistrationBean {
	private UserRepository repository;

	public RegistrationBean(){


	public UserRepository getRepository() {
		return repository;

	public void setRepository(UserRepository repository) {
		this.repository = repository;

And use the element component-scan for determining the required bean. By using Spring Data repository you have the same ability that Mongo Template offers.

Maven Configuration

To configure using of MongoTemplate or Spring Data repository, you have to add the below dependencies in your maven configurations.


		<!-- Dependency for MongoDB Java connector -->
		<!-- Spring Data Mongo Support -->
		<!--  Spring Data commons -->

Spring Data MongoDB Example Application

Find below the Spring Data MongoDB application that should persist two documents of type User into MongoDB.


package net.javabeat.springdata.executable;

import net.javabeat.springdata.beans.RegistrationBean;
import net.javabeat.springdata.jpa.data.Address;
import net.javabeat.springdata.jpa.data.User;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;

public class Executable {
	public static RegistrationBean registrationBean;
	public static ClassPathXmlApplicationContext context;

	static {
		// Acquire Context
		context = new ClassPathXmlApplicationContext("SpringContext.xml");

	public static void main(String [] args) throws Exception{
		// Create by MongoTemplate
		// Create By Spring Data

	public static void createUserThroughMonogoTamplate(){
		MongoTemplate mongoOps = (MongoTemplate)context.getBean("mongoTemplate");
		User user = new User();
		user.setFullName("Mongo Template");
		Address address = new Address();

	public static void CreateUserThoughMongoRepository(){
		User user = new User();
		user.setFullName("Spring Data");
		Address address = new Address();
		RegistrationBean bean = (RegistrationBean)context.getBean("registrationBean");

Saved Documents

The below snapshot shows you the documents that are saved into MongoDB.
Spring Data MongoDB


Spring Data provides you an awesome ways for integrating the MongoDB. Regardless of using MongoTemplate that already provided by Spring iteself, Spring Data provides a special repository for being used with the MongoDB. Those repositories provides you a full access of inserting, deleting, updating and reading the documents from MongoDB’s collections without any need for care about the implementation.


Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!