Over a million developers have joined DZone.

Spring Data MongoDB Hello World with Spring MVC: Example

This article presents detailed steps on what is needed to get started with Spring Data MongoDB while you are working with a Spring MVC web application.

Build fast, scale big with MongoDB Atlas, a hosted service for the leading NoSQL database. Try it now! Brought to you in partnership with MongoDB.

This article presents detailed steps on what is needed to get started with Spring Data MongoDB while you are working with a Spring MVC web application. The article assumes that you have got the 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"
<strong>     http://www.springframework.org/schema/data/mongo

<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">

<strong><!-- 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() );

Now it's easier than ever to get started with MongoDB, the database that allows startups and enterprises alike to rapidly build planet-scale apps. Introducing MongoDB Atlas, the official hosted service for the database on AWS. Try it now! Brought to you in partnership with MongoDB.

nosql ,mvc ,mongodb ,spring data ,database

Published at DZone with permission of Ajitesh Kumar. See the original article here.

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 }}