Spring Data MongoDB hello world example

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.

SpringData-helloworld-example

2. Dependency

The following libraries are required :

spring-data-mongodb
Currently, the “spring-data-mongodb” jar is only available in “http://maven.springframework.org/milestone“, 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.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
	http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mkyong.core</groupId>
	<artifactId>SpringMongoDBExample</artifactId>
	<packaging>jar</packaging>
	<version>1.0</version>
	<name>SpringMongoExample</name>
	<url>http://maven.apache.org</url>
 
	<dependencies>
 
		<!-- Spring framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
 
		<!-- mongodb java driver -->
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.11.0</version>
		</dependency>
 
		<!-- Spring data mongodb -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.2.0.RELEASE</version>
		</dependency>
 
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2.2</version>
		</dependency>
 
	</dependencies>
 
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
				</configuration>
			</plugin>
		</plugins>
	</build>
 
</project>

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.

Note
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.

SpringMongoConfig.java
package com.mkyong.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
 
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
 
@Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration {
 
	@Override
	public String getDatabaseName() {
		return "yourdb";
	}
 
	@Override
	@Bean
	public Mongo mongo() throws Exception {
		return new MongoClient("127.0.0.1");
	}
}

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

SpringMongoConfig1.java
package com.mkyong.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
 
import com.mongodb.MongoClient;
 
@Configuration
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

SpringConfig.xml
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
	<mongo:mongo host="127.0.0.1" port="27017" />
	<mongo:db-factory dbname="yourdb" />
 
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
	</bean>
 
</beans>

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.

User.java
package com.mkyong.model;
 
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
 
@Document(collection = "users")
public class User {
 
	@Id
	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.

App.java
package com.mkyong.core;
 
import java.util.List;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
 
import com.mkyong.config.SpringMongoConfig;
import com.mkyong.model.User;
//import org.springframework.context.support.GenericXmlApplicationContext;
 
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
	mongoOperation.save(user);
 
	// 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
	mongoOperation.updateFirst(searchUserQuery, 
                         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());
 
    }
 
}

Output

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 – SpringMongoDB-HelloWorld-Example.zip (24 KB)

References

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

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: Instagram likes kopen()

  • Pingback: water ionizer machines()

  • Pingback: car parking()

  • Pingback: car parking()

  • Pingback: mp4 mobile porn()

  • Pingback: check out DIRECTV channels()

  • Pingback: Direct TV vs Dish TV()

  • Pingback: Blue Coaster33()

  • Pingback: spring data mongodb 1.0.2.RELEASE | Just do it.()

  • Greg

    I get org/springframework/dao/InvalidDataAccessApiUsageException. Isn’t this a relic of Spring 2?

  • Maxim

    seems this is invalid:

    there is no ‘mongoDbFactory’

  • JJ Zabkar

    FYI, the link in section 3 is broken (“hhttp”).

    • http://www.mkyong.com mkyong

      Fixed, thanks.

  • Pingback: Java MongoDB Tutorial()

  • Pingback: Spring Data MongoDB : Save binary file, GridFS example()

  • Pingback: Spring Data MongoDB : Update document()

  • Pingback: Spring Data MongoDB : Insert document()

  • Haris

    Thank you for the sample,

    It is simple and well understandable.

  • http://www.mkyong.com/java/jce-encryption-data-encryption-standard-des-tutorial/ Srinivasa HP

    Pls let us know how to close the mongoDB connection.
    FYI – we are using Spring Data to connect to mongoDB

    • http://www.mkyong.com mkyong

      If not mistake, SpringData will handle it, no need to close or release the MongoDB connection manually.

  • http://www.facebook.com/hans.herrerabravo Hans Herrera Bravo

    persist data? with implementation DataNucleus?

  • Vincent

    Can you show us how to close the mongoDB connection in this example ?

  • Bob Marks

    The Spring XML config isn’t quite correct – its missing a “mongo-ref” attribute. For example, if your Mongo database is on another server. i.e.

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

    It won’t connect (always defaults to localhost) so you have to update the

    <mongo:db-factor>

    XML to look like the following: –

    <mongo:db-factory dbname="test" mongo-ref="mkyong" />

    Nice example all the same!

  • Pingback: spring data mongodb 1.0.2.RELEASE | Just do it.()

  • Pingback: Converting to MongoDB » Agile Mobile Developer()

  • mark

    what about updating multiple fields at once? I can’t seem to find an example of this anywhere with spring data.

  • C

    Solid intro tutorial, thank you mkyong. I had to make some updates to get it working with the latest versions. In particular, the package names are now org.springframework.data.mongodb.core and most of the calls require the collection name last, not first. Here is a working version of the “App” class (and note that you have to modify the above spring config to 1) correct the package name, and 2) remove that last constructor parameter!)…:

    package com.mkyong.core;
     
    import java.util.List;
     
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import org.springframework.context.support.GenericXmlApplicationContext;
    import org.springframework.data.mongodb.core.MongoOperations;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    import org.springframework.data.mongodb.core.query.Update;
     
    import com.mkyong.config.SpringMongoConfig;
    import com.mkyong.model.User; // I changed this to match my own preference
     
    public class App
    {
        public static final String COLLECTION = &quot;user-info&quot;;
     
        public static void main( String[] args )
        {
        	//For Annotation
        	//ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
     
        	//For XML
        	ApplicationContext ctx = new GenericXmlApplicationContext(&quot;spring-config.xml&quot;);
     
        	MongoOperations mongoOperation = (MongoOperations)ctx.getBean(&quot;mongoTemplate&quot;);
     
            User user = new User(&quot;1001&quot;, &quot;first&quot;, &quot;name&quot;, 40);
     
            //save
            mongoOperation.save(user,COLLECTION);
     
            //find
            User savedUser = mongoOperation.findOne(new Query(Criteria.where(&quot;id&quot;).is(&quot;1001&quot;)),
    				User.class,COLLECTION);
     
            System.out.println(&quot;savedUser : &quot; + savedUser);
     
            //update
            mongoOperation.updateFirst(
            		new Query(Criteria.where(&quot;firstname&quot;).is(&quot;first&quot;)), 
            		Update.update(&quot;lastname&quot;, &quot;new lastname&quot;),COLLECTION);
     
            //find
            User updatedUser = mongoOperation.findOne(
            		new Query(Criteria.where(&quot;id&quot;).is(&quot;1001&quot;)),
    				User.class,COLLECTION);
     
            System.out.println(&quot;updatedUser : &quot; + updatedUser);
     
            //delete
            mongoOperation.remove(
            		new Query(Criteria.where(&quot;id&quot;).is(&quot;1001&quot;)),
            		COLLECTION);
     
            //List
            List&lt;User&gt; listUser =  
            	mongoOperation.findAll(User.class,COLLECTION);
            System.out.println(&quot;Number of user = &quot; + listUser.size());
     
        }
     
    }
    • http://www.l.com wfqwf
      import com.mkyong.config.SpringMongoConfig;
      import com.mkyong.model.User; // I changed this to match my own preference
       
      public class App
      {
          public static final String COLLECTION = &quot;user-info&quot;;
       
          public static void main( String[] args )
          {
          	//For Annotation
          	//ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
       
          	//For XML
          	ApplicationContext ctx = new GenericXmlApplicationContext(&quot;spring-config.xml&quot;);
       
          	MongoOperations mongoOperation = (MongoOperations)ctx.getBean(&quot;mongoTemplate&quot;);
       
              User user = new User(&quot;1001&quot;, &quot;first&quot;, &quot;name&quot;, 40);
       
              //save
              mongoOperation.save(user,COLLECTION);
       
              //find
              User savedUser = mongoOperation.findOne(new Query(Criteria.where(&quot;id&quot;).is(&quot;1001&quot;)),
      				User.class,COLLECTION);
       
              System.out.println(&quot;savedUser : &quot; + savedUser);
       
              //update
              mongoOperation.updateFirst(
              		new Query(Criteria.where(&quot;firstname&quot;).is(&quot;first&quot;)), 
              		Update.update(&quot;lastname&quot;, &quot;new lastname&quot;),COLLECTION);
       
              //find
              User updatedUser = mongoOperation.findOne(
              		new Query(Criteria.where(&quot;id&quot;).is(&quot;1001&quot;)),
      				User.class,COLLECTION);
       
              System.out.println(&quot;updatedUser : &quot; + updatedUser);
       
              //delete
              mongoOperation.remove(
              		new Query(Criteria.where(&quot;id&quot;).is(&quot;1001&quot;)),
              		COLLECTION);
       
              //List
              List listUser =  
              	mongoOperation.findAll(User.class,COLLECTION);
              System.out.println(&quot;Number of user = &quot; + listUser.size());
       
          }
       
      }
    • http://www.mkyong.com mkyong

      Thanks, article is updated to use v1.0.4.RELEASE

    • http://www.mkyong.com mkyong

      Article is updated to SpringData v 1.2.0.RELEASE , APIs are updated very fast…

      • http://compare-tech.blogspot.in Triguna

        Ahh!! With the latest release of spring-data-mongo… there exists a serious bug… Check here: https://jira.springsource.org/browse/DATAMONGO-716

        I think its better we use the old one. However I am not getting exact mongo tags for the same, can u please update here if you have the backup?

  • http://mykong paparao

    mongoTemplate save does not return the created document. In my case I leave the primary id generation to the mongodb. So I need the created document so that I can get the id that is generated.

    Why the insert method does not return the created document.

    • http://www.mkyong.com mkyong

      Refer to above example. The object you saved / inserted will contains the _id automatically.

      • Anoop

        Hi,

        The _id is being generated, but I want to use the generated id, like you have in the Sysout.

        // save
        mongoOperation.save(user);

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

        The problem is that persisted object doesn’t have the id, but when I go and check in the DB it has been generated. Could you please tell me if I am missing anything? I want to access that id like you have in the sysout.

        FYI, I am using MongoTemplate, not MongoOperation like you have, if that makes any difference.

  • vemv

    that is some seriously ugly code.

    • whirlwin

      Welcome to Java!

      • ajit

        you are so right!

  • Livingston.Chen

    how to authenticate?

    • Vinko Celepirovic

      How to authenticate? That’s a good question.
      I made an example with the user registration and user authentication and more. When a web service on my PC’s available you can freely test. (Send me a message if service is unavailable.) Hope you will like this example.

      You can try demo on address:
      http://vanadad.dyndns-web.com:8083/extsecdemo/

      • Vinko Celepirovic

        Sorry! I changed ports etc. Demo is on address:
        http://vanadad.dyndns-web.com/extsecdemo/

        • CJM

          Could you open source this so people can see it and not rely on your personal dynamic dns?

        • http://www.mkyong.com mkyong

          May be you should upload to github, it’s free :)

  • Pingback: Spring & MongoDB?? - CloudCode()