Spring Data MongoDB Hello World with Spring MVC – Example

The article presents detailed steps on what is needed to get started with Spring Data MongoDB while you are working with Spring MVC web application. The article assumes that you have got Spring MVC application setup done.
Step 1: Create Documents in MongoDB

One could download MongoDB from http://www.mongodb.org/downloads page. Once downloaded, do the following to get started.

  • Open a command prompt & goto bin folder found within MongoDB root folder.
  • Before starting MongoDB server, create the data directory within root folder.
  • Start the MongoDB server with command such as “mongod -dbpath <path-to-mongodb-root-folder>”
  • Open another command prompt and goto bin folder.
  • Execute “mongo” command and you are all set. Access various DB commands at http://docs.mongodb.org/manual/reference/command/.
  • As there is no command to create the database, give “use testdb” and testdb would be created.
  • Create a collection using following command – db.createCollection( “users” )
  • Check whether the collection is created by executing “show collections” command.
  • Insert records using command: db.runCommand( { insert: “users”, documents: [ { _id: 1, firstname: “ajitesh”, lastname: “shukla” }] } )
  • Check the document using command, db.testdb.find()


Step 2: Spring Data MongoDB Libraries

Download following libraries and place them within WEB-INF/lib folder and the classpath. These are latest libraries at the time of writing the blog.


Step 3: Create Users Class

Create User class pertaining to “users” document within MongoDB. Following is the sample code:

package com.vitalflux.hellomongo;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

public class Users {

    private String id;

    private String firstname;
    private String lastname;

    public Users() {}

    public Users(String firstName, String lastName) {
        this.firstname = firstName;
        this.lastname = lastName;

	 * @return the id
	public String getId() {
		return id;

	 * @param id the id to set
	public void setId(String id) {
		this.id = id;

	 * @return the firstName
	public String getFirstName() {
		return firstname;

	 * @param firstName the firstName to set
	public void setFirstName(String firstName) {
		this.firstname = firstName;

	 * @return the lastName
	public String getLastName() {
		return lastname;

	 * @param lastName the lastName to set
	public void setLastName(String lastName) {
		this.lastname = lastName;



Step 4: Create UsersRepository Interface
package com.vitalflux.mongo.repositories;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.vitalflux.hellomongo.Users;

public interface UsersRepository extends MongoRepository<Users, String>{


Step 5: Create A Controller
package com.vitalflux.hellomongo;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.vitalflux.mongo.repositories.UsersRepository;

public class HelloMongoController {

	private UsersRepository repository;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView helloWorld( ModelMap model ) {
		List users = repository.findAll();

		ModelAndView modelAndView = new ModelAndView("index");		
		modelAndView.addObject("users", users );
		return modelAndView;


Step 6: Configure Spring-Servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

<context:component-scan base-package="com.vitalflux.hellomongo" />
<context:component-scan base-package="com.vitalflux.mongo.repositories" />

     <!-- Configuration defining views files -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
    <property name="suffix">

<!-- Factory bean that creates the Mongo instance -->
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
    <property name="host" value="localhost" />

<!-- MongoTemplate for connecting and quering the documents in the database -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
     <constructor-arg name="mongo" ref="mongo" />
     <constructor-arg name="databaseName" value="test" />

<mongo:repositories base-package="com.vitalflux.mongo.repositories" />



Step 7: Create A View, index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.List"%>
<%@ page import="com.vitalflux.hellomongo.Users"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
List<Users> users = (List<Users>) request.getAttribute( "users" );
for (Users user : users) {
pageContext.setAttribute("firstname", user.getFirstName() );


Ajitesh Kumar
Follow me

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking
Posted in Java, NoSQL. Tagged with , , .

3 Responses

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.