Spring MVC and MongoDB tutorial


This tutorial has the goal to show how can be easy to create a new Web application based on Spring and MongoDB.

You can find the code of this small application here:


The prerequisite is to have MongoDB installed and started.

Spring has a module to import all the necessary for MongoDB:


In the servlet-context we configure the connection to the database and we create the template that we will use to interact with it:

<mongo:mongo id="mongo" host="localhost" port="27017"/> 
   <beans:bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> 
       <beans:constructor-arg ref="mongo"/> 
       <beans:constructor-arg name="databaseName" value="jobfinder"/> 
   <mongo:repositories base-package="ch.genidea.mvcMongoExample.repository"/> 

Here you can see how simple his our class structure:

File structure of the project

We use a Person class to store the data in the database:

import org.bson.types.ObjectId; 
import org.springframework.data.annotation.Id; 
import org.springframework.data.mongodb.core.mapping.Document; 
public class Person { 
    private ObjectId id; 
    private String username; 
    private String password; 
    public Person() { 

For MongoDB we use the annotation @Document in place of the more traditional @Entity used for traditional databases.

In MainMongo.java you can find an example about how to use the Person class.

 public class MainMongo { 
    private static final Logger log = LoggerFactory.getLogger(MainMongo.class); 
    public static void main(String[] args) throws Exception { 
        MongoOperations mongoOperations = new MongoTemplate(new Mongo(), "database"); 
        mongoOperations.insert(new Person("marco", "marco")); 
        Person person = mongoOperations.findOne(new Query(Criteria.where("username").is("marco")), Person.class); 
        log.debug("Person found :" + person.getUsername()); 

To update the database we can leverage the power of spring data. It’s enough to create an interface that extends CrudRepository to have basic db features magically available:

import ch.genidea.mvcMongoExample.model.Person; 
import org.springframework.data.repository.CrudRepository; 
import java.util.List; 
public interface PersonRepository extends CrudRepository<Person, Long> { 
    List<Person> findByUsername(String username); 

The interface is used in our HomeController to retrieve the list of people records in the database:

private PersonRepository personRepository; 
 * Home page renderer 
@RequestMapping(value ="/", method = RequestMethod.GET) 
public String home(Locale locale, Model model) { 
    logger.info("Home page"); 
    Iterable<Person> personList = personRepository.findAll(); 
    model.addAttribute("personList", personList); 

Here the result:

result example result

Alternatively we can use MongoTemplate as in the MainMongo class or in the PersonController where we mix MongoTemplate and CrudRepository just to show the possibilities that Spring give to the developer:

We have a very poor page that allows to add a new Person:

browser result

when the user click on Save the method addPerson is called:

MongoTemplate mongoTemplate; 
PersonRepository personRepository; 
@RequestMapping(value ="/savePerson", method = RequestMethod.POST) 
public String addPerson(@ModelAttribute("person") Person person, BindingResult result) { 
    List personList = personRepository.findByUsername(person.getUsername()); 
    if (personList.size() > 0) { 
        System.out.println("Error username already exists"); 
    } else { 
        System.out.println("Ok: new username"); 
    return "redirect:/"; 

WebApp built by Marco using SpringBoot 3 and Java 21. App hosted in Switzerland.