Over a million developers have joined DZone.

Spring Data & MongoDB

DZone's Guide to

Spring Data & MongoDB

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

 In this article we are going to cover the following topics:

  1. MongoDB Installation on Windows Machine.
  2. MongoDB Java Example.
  3. Spring Data & MongoDB.

  MongoDB Installation on Windows Machine:

     Download MongoDB from official MongoDB website.

     Unzip MongoDB files to your prefer location, for example : “D:\mongodb-win32-x86_64-1.8.3“.

     MongoDB won’t create data directory automatically. You need to create a data directory for MongoDB, for example : “D:\mongodb-data“.

    mongod.exe is the database server daemon, run it and point it to the data directory, via “--dbpath” argument.

  D:\mongodb-win32-x86_64-1.8.3\bin>mongod --dbpath "D:\mymongodb-data" 

   In the output, you will notice that MongoDB started a web admin interface listening on port 28017.

   To access it, just type http://your-ipaddress:28017.

   In order to connect to your MongoDB server type D:\mongodb-win32-x86_64-1.8.3\bin>mongo

   If you are able to view the MongoDB web admin interface and also connected to the database server via mongo.exe, then your MongoDB is installed on the Windows successfully.


  MongoDB Java Example:

    A simple Java MongoDB example.

    Technologies and tools used:

  1. MongoDB 1.8.3
  2. MongoDB-Java-Driver 2.6.5
  3. JDK 1.6


package edu.seua.mongo;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

* Java MongoDB Example
public class MongoApp {

public static void main(String[] args) {

try {
// connect to mongoDB
Mongo mongo = new Mongo("localhost", 27017);

// if database doesn't exists, mongoDB will create it
DB db = mongo.getDB("mydb");

// Get collection from MongoDB, database named "mydb"
// if collection doesn't exists, mongoDB will create it
DBCollection collection = db.getCollection("myCollection");

// create a document to store attributes
BasicDBObject document = new BasicDBObject();
document.put("id", 100);
document.put("name", "simple name");
document.put("message", "simple message");

// save it into collection named "myCollection"

// search query
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("id", 100);

DBCursor cursor = collection.find(searchQuery);

// loop over the cursor and display the result
while (cursor.hasNext()) {

} catch (UnknownHostException e) {
} catch (MongoException e) {



"_id" : { "$oid" : "4e5936ca602fbf0c50e0c9d0"} ,
"id" : 100 , "name" : "simple name" , "message" : "simple message"


   Now it's time for Spring Data & MongoDB:

    Technologies and jars used:

  1. MongoDB 1.8.3
  2. JDK 1.6
  3. mongo-2.6.5.jar
  4. org.springframework.context-3.0.5.RELEASE.jar
  5. org.springframework.core-3.0.5.RELEASE.jar
  6. org.springframework.beans-3.0.5.RELEASE.jar
  7. commons-logging-1.1.1.jar
  8. org.springframework.asm-3.0.5.RELEASE.jar
  9. spring-data-mongodb-1.0.0.M2.jar
  10. slf4j-api-1.6.1.jar
  11. slf4j-jdk14-1.6.1.jar
  12. spring-dao-2.0.8.jar
  13. spring-expression-3.1.0.M2.jar
  14. spring-data-commons-core-1.1.0.M1.jar
  15. spring-tx-3.1.0.M1.jar
  16. spring-data-document-core-1.0.0.M2.jar

Spring XML configuration file (mongo-config.xml):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

<mongo:mongo host="localhost" port="27017" />

<bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="myNewdb" />
<constructor-arg name="defaultCollectionName" value="myNewCollection" />

<!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
<context:annotation-config />


  Let's create Employee DTO

package edu.seua.mongo;

public class Employee {

private String id;
private String firstname;
private String lastname;
private int age;

public Employee() {

public Employee(String id, String firstname, String lastname, int age) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.age = age;

public String getId() {
return id;

public void setId(String id) {
this.id = id;

public String getFirstname() {
return firstname;

public void setFirstname(String firstname) {
this.firstname = firstname;

public String getLastname() {
return lastname;

public void setLastname(String lastname) {
this.lastname = lastname;

public int getAge() {
return age;

public void setAge(int age) {
this.age = age;

public String toString() {
return "Employee [age=" + age + ", firstname=" + firstname + ", id="
+ id + ", lastname=" + lastname + "]";


  Full Example   

    Full example shows you how to use Spring data to perform CRUD operations in mongoD.

    The employee object is saved into a collection named employees.

package edu.seua.mongo;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.document.mongodb.MongoOperations;
import org.springframework.data.document.mongodb.query.Criteria;
import org.springframework.data.document.mongodb.query.Query;
import org.springframework.data.document.mongodb.query.Update;

* Java Spring Data & MongoDB Example
public class SpringDataMongoApp {

public static void main(String[] args) {

ApplicationContext ctx = new ClassPathXmlApplicationContext("edu/seua/mongo/mongo-config.xml");

MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

Employee employee = new Employee("100", "firstName", "lastName", 23);

// save
mongoOperation.save("employees", employee);

// find
Employee savedEmployee = mongoOperation.findOne("employees", new Query(Criteria.where(
"id").is("100")), Employee.class);

System.out.println("Saved Employee: " + savedEmployee);

// update
mongoOperation.updateFirst("employees", new Query(Criteria.where(
"firstname").is("firstName")), Update.update("lastname",
"new lastName"));

// find
Employee updatedEmployee = mongoOperation.findOne("employees", new Query(
Criteria.where("id").is("100")), Employee.class);

System.out.println("Updated Employee: " + updatedEmployee);

// delete
mongoOperation.remove("employees", new Query(Criteria.where("id").is(
"100")), Employee.class);

// List
List<Employee> listEmployee = mongoOperation.getCollection("employees", Employee.class);
System.out.println("size of employees = " + listEmployee.size());




Saved Employee: Employee [age=23, firstname=firstName, id=100, lastname=lastName]
Updated Employee: Employee [age=23, firstname=firstName, id=100, lastname=new lastName]
size of employees = 0


Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}