springboot-SpringBoot 2 and mongodb CRUD example

1. Introduction

This article would demo how to use SpringBoot 2 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:

@Document(collection = "customers")
public class Customer {
    private Long id;

    @Indexed(unique = true)
    private String code;// the code should be unique for every customer

    private String firstName;
    private String lastName;
    private int age;

    public Customer() {}

    public Customer(Long id,String code,String firstName, String lastName) {
        this.id = id;
        this.code = code;
        this.firstName = firstName;
        this.lastName = lastName;

    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", code='" + code + '\'' +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age=" + age +
    //getters and setters

It’s very simple:

  • the @Id indicates that the id is the MongoDB’s primary key
  • the @Indexed means the code column would be indexed and keep unique

3.3 Define your MongoRepository

We should define a custom class which extends the MongoRepository to get the abilities of spring data mongodb.

public interface CustomerRepository extends MongoRepository<Customer, Long> {
    Customer findByCode(String code);
    List<Customer> findByLastName(String lastName);

The MongoRepository<Customer, Long> means:

  • Our MongoDB document class is an instance of Customer
  • Our MongoDB document id is an instance of Long

The parent class MongoRepository has many good features that you can use:

image desc

3.4 Configure by application.properties



3.5 Write a CommandLineRunner to test your code

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

    private CustomerRepository repository;

    public void run(String... strings) throws Exception {

        // save a couple of customers
        repository.save(new Customer(1l,"001","Alice", "Smith"));
        repository.save(new Customer(2l,"002","Bob", "Smith"));

        // fetch all customers
        logger.info("Customers found with findAll():");
        for (Customer customer : repository.findAll()) {

        // fetch and update an individual customer
        logger.info("Customer found with findByCode('001'):");
        Customer theCustomer = repository.findByCode("001");
        Customer theCustomer2 = repository.findByCode("001");
        logger.info("updated customer:"+theCustomer2.toString());

        logger.info("Customers found with findByLastName('Smith'):");
        for (Customer customer : repository.findByLastName("Smith")) {

Run the SpringBoot app and we would get this result: image desc

4. Summary

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