In this tutorial, we show you how to use “SpringData for MongoDB” framework, to perform CRUD operations in MongoDB, via Spring’s annotation and XML schema.

Updated on 1/04/2013
Article is updated to use latest SpringData v 1.2.0.RELEASE, it was v1.0.0.M2.

Tools and technologies used :

  1. Spring Data MongoDB – 1.2.0.RELEASE
  2. Spring Core – 3.2.2.RELEASE
  3. Java Mongo Driver – 2.11.0
  4. Eclipse – 4.2
  5. JDK – 1.6
  6. Maven – 3.0.3

P.S Spring Data requires JDK 6.0 and above, and Spring Framework 3.0.x and above.

1. Project Structure

A classic Maven’s style Java project directory structure.


2. Dependency

The following libraries are required :

Currently, the “spring-data-mongodb” jar is only available in ““, so, you have to declare this repository also.

Updated on 13/09/2012
spring-data-mongodb is available at the Maven central repository, Spring repository is no longer required.


<project xmlns="" 


		<!-- Spring framework -->


		<!-- mongodb java driver -->
		<!-- Spring data mongodb -->





3. Spring Configuration, Annotation and XML

Here, we show you two ways to configure Spring data and connect to MongoDB, via annotation and XML schema.

Refer to this official reference Connecting to MongoDB with Spring.

3.1 Annotation
Extends the AbstractMongoConfiguration is the fastest way, it helps to configure everything you need to start, like mongoTemplate object.

package com.mkyong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;

public class SpringMongoConfig extends AbstractMongoConfiguration {

	public String getDatabaseName() {
		return "yourdb";

	public Mongo mongo() throws Exception {
		return new MongoClient("");

Alternatively, I prefer this one, more flexible to configure everything.

package com.mkyong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mongodb.MongoClient;

public class SpringMongoConfig1 {

	public @Bean
	MongoDbFactory mongoDbFactory() throws Exception {
		return new SimpleMongoDbFactory(new MongoClient(), "yourdb");

	public @Bean
	MongoTemplate mongoTemplate() throws Exception {
		MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
		return mongoTemplate;


And load it with AnnotationConfigApplicationContext :

    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");

3.2 XML Schema


<beans xmlns=""


	<mongo:mongo host="" port="27017" />
	<mongo:db-factory dbname="yourdb" />

	<bean id="mongoTemplate" class="">
		<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />


And include it with Spring’s GenericXmlApplicationContext :

   ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
   MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");	
So, XML or Annotation?
Actually, both are doing the same thing, it’s just based on personal preferences. Personally, I like XML to configure things.

4. User Model

An User object, annotated @Document – which collection to save. Later, we show you how to use Spring data to bind this object to / from MongoDB.

package com.mkyong.model;


@Document(collection = "users")
public class User {

	private String id;

	String username;

	String password;
	//getter, setter, toString, Constructors


5. Demo – CRUD Operations

Full example to show you how to use Spring data to perform CRUD operations in MongoDB. The Spring data APIs are quite clean and should be self-explanatory.

package com.mkyong.core;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.mkyong.config.SpringMongoConfig;
import com.mkyong.model.User;

public class App {

    public static void main(String[] args) {

	// For XML
	//ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");

	// For Annotation
	ApplicationContext ctx = 
             new AnnotationConfigApplicationContext(SpringMongoConfig.class);
	MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

	User user = new User("mkyong", "password123");

	// save;

	// now user object got the created id.
	System.out.println("1. user : " + user);

	// query to search user
	Query searchUserQuery = new Query(Criteria.where("username").is("mkyong"));

	// find the saved user again.
	User savedUser = mongoOperation.findOne(searchUserQuery, User.class);
	System.out.println("2. find - savedUser : " + savedUser);

	// update password
                         Update.update("password", "new password"),User.class);

	// find the updated user object
	User updatedUser = mongoOperation.findOne(searchUserQuery, User.class);

	System.out.println("3. updatedUser : " + updatedUser);

	// delete
	mongoOperation.remove(searchUserQuery, User.class);

	// List, it should be empty now.
	List<User> listUser = mongoOperation.findAll(User.class);
	System.out.println("4. Number of user = " + listUser.size());




1. user : User [id=516627653004953049d9ddf0, username=mkyong, password=password123]
2. find - savedUser : User [id=516627653004953049d9ddf0, username=mkyong, password=password123]
3. updatedUser : User [id=516627653004953049d9ddf0, username=mkyong, password=new password]
4. Number of user = 0

Download Source Code

Download it – (24 KB)


  1. Spring data for MongoDB
  2. Connecting to MongoDB with Spring
  3. Oreilly Spring data mongodb tutorial
  4. Another good Spring data mongodb tutorial