Tuesday, 19 November 2013

Spring Data Mongodb CRUD operation using MongoTemplate


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 for new datastores while retaining store-specific features and capabilities. See more about SpringData

In this example we will see simple CRUD operation using SpringData MongoTemplate.

Prerequisites: Mongodb should up and running

1. Create a Maven Project

Create a Maven project and add below dependencies

<project xmlns="" xmlns:xsi=""
			<name>Spring Maven MILESTONE Repository</name>
		<!-- mongodb java driver -->

2. Create a Main class for CRUD operations

package com.pretech;
import com.mongodb.Mongo;
public class SpringDataMongoTemplate {
	public static void main(String[] args) {
		Mongo mongo;
		try {
			mongo = new Mongo("localhost");
			MongoTemplate mongoTemplate = new MongoTemplate(mongo,
			// Create Collections
			if (!mongoTemplate.collectionExists("Students")) {
			System.out.println("Collection created "+mongoTemplate.getCollectionNames());
			// Insert Student details Student("Santhosh", "Bangalore"));
			// Select student details
			System.out.println("Student details after insert"
					+ mongoTemplate.findAll(Student.class));
			// Update Student Details
					new Query(Criteria.where("name").is("Santhosh")),
					Update.update("address", "New Bangalore"), Student.class);
			System.out.println("Student details after update"
					+ mongoTemplate.findAll(Student.class));
			// Delete Student details
			mongoTemplate.remove(new Query(Criteria.where("name")
			System.out.println("Student details after Delete"
					+ mongoTemplate.findAll(Student.class));
		} catch (Exception e) {
			// TODO Auto-generated catch block
class Student {
	String name;
	String address;
	public Student(String name, String address) {
		super(); = name;
		this.address = address;
	public String getName() {
		return name;
	public void setName(String name) { = name;
	public String getAddress() {
		return address;
	public void setAddress(String address) {
		this.address = address;
	public String toString() {
		return "Student [name=" + name + ", address=" + address + "]";

Run it

Console output

Collection created [Students, system.indexes]
Student details after insert[Student [name=Santhosh, address=Bangalore]]
Student details after update[Student [name=Santhosh, address=New Bangalore]]
Student details after Delete[]