springboot-SpringBoot 2 and mongotemplate CRUD example

-SpringBoot 2 and mongodb CRUD example using MongoRepository

1. Introduction

This article would demo how to use SpringBoot’s mongotemplate to do simple CRUD(create-read-update-delete) operations on MongoDB.

2. Environments

  • SpringBoot 2.x
  • MongoDB
  • jdk 1.8

3. The example

3.1 Define dependency in your pom

Add spring data mongodb to your pom like this:

                <!-- Import dependency management from Spring Boot -->


3.2 Define your domain class

Let’s define a domain class that would map to MongoDB document like this:

package hello.mongo.domain;

public class Person {
    private int id;
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;

    public int getId() {
        return id;

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

    public String getName() {
        return name;

    public void setName(String name) {
        this.name = name;

    public int getAge() {
        return age;

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

    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +

3.3 Define your MongoDB Config class

We should define a config class to access MongoDB.

package hello.mongo.dao;

import com.mongodb.MongoClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;

public class MongoConfig extends AbstractMongoConfiguration {
    private String databaseName;

    private String host;

    private int port;

    public @Bean MongoClient mongoClient() {
        return new MongoClient(host,port);

    public @Bean
    MongoTemplate mongoTemplate() throws Exception {
        MongoTemplate template =  new MongoTemplate(mongoDbFactory(), mappingMongoConverter());
        return template;

    protected String getDatabaseName() {
        return databaseName;

It’s very simple:

  • It’s a @Configuration class which indicates this class has some bean definitions.
  • It extends the AbstractMongoConfiguration to extend and do some customizations on MongoDB configurations.
  • It uses @Value annotation to read MongoDB configrations from application.properties
  • The most important is that this class return a MongoTemplate class to be used to access MongoDB

3.4 Configure by application.properties



3.5 Write a CommandLineRunner to test your code

package hello.mongo.commands;

import hello.mongo.domain.Person;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Component;

import java.util.List;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.core.query.Update.update;

public class MyMongoTemplateCommand implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(MyMongoTemplateCommand.class);

    private MongoOperations mongoOperations;

    public void run(String... strings) throws Exception {
        if(mongoOperations!=null) {
            Person p = new Person("Joe", 34);

            // Insert is used to initially store the object into the database.
            logger.info("Insert: " + p);

            // Find
            p = mongoOperations.findById(p.getId(), Person.class);
            logger.info("Found: " + p);

            // Update
            mongoOperations.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);
            p = mongoOperations.findOne(query(where("name").is("Joe")), Person.class);
            logger.info("Updated: " + p);

            // Delete

            // Check that deletion worked
            List<Person> people =  mongoOperations.findAll(Person.class);
            logger.info("Number of people = : " + people.size());


4. Summary

You can see that spring data mongotemplate makes the mongodb operations more simpler.