DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Spring Boot Application With Spring REST and Spring Data MongoDB
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Introduction to Spring Boot and JDBCTemplate: Refactoring to SpringData JPA

Trending

  • Exactly-Once Processing: Myth vs Reality
  • Introduction to Tactical DDD With Java: Steps to Build Semantic Code
  • Chaos Engineering Has a Blind Spot. Agentic AI Lives in It.
  • Stateless JWT Auth Microservice Architecture With Spring Boot 3 and Redis Sentinel
  1. DZone
  2. Data Engineering
  3. Databases
  4. Spring Data: Easy MongoDB Migration Using Mongock

Spring Data: Easy MongoDB Migration Using Mongock

In this tutorial, we will learn how to manage and apply MongoDB database schema changes using Mongock.

By 
Anicet Eric user avatar
Anicet Eric
·
Jun. 11, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
27.6K Views

Join the DZone community and get the full member experience.

Join For Free

In one of my projects, I was looking for some simple options to manage MongoDB database schema changes similar to other projects like Flyway or Liquibase. I found Mongock, which is an open-source Java MongoDB tool.

Prerequisites

  • Spring Boot 2.5.0
  • Maven 3.6.1
  • JAVA 11
  • Mongo 4.4

Getting Started

We will start by creating a simple Spring Boot project from start.spring.io, with the following dependencies: Web, MongoDB, and Lombok.

To start using Mongock in our project, we need to add the dependencies below in the pom.xml file.

  • Import the last version of Mongock's bom to your pom file. You can check the latest version here.
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.github.cloudyrock.mongock</groupId>
            <artifactId>mongock-bom</artifactId>
            <version>4.3.8</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>


  • Add the runner dependency. 
<dependency>
    <groupId>com.github.cloudyrock.mongock</groupId>
    <artifactId>mongock-spring-v5</artifactId>
</dependency>


  • Add the driver dependency.
<dependency>
    <groupId>com.github.cloudyrock.mongock</groupId>
    <artifactId>mongodb-springdata-v3-driver</artifactId>
</dependency>

Enable Mongock

Once you have successfully imported the necessary dependencies, there are two ways to activate Mongock in our project. In most cases, when using the Spring framework, the easiest and most convenient way is the annotation approach. However, sometimes you don't use Spring or you need more control over your Mongock bean. In this case, you should go for the traditional builder approach.

We opt for the annotation approach in our project.

  • Add the @EnableMongock annotation to the main class.

Add @EnableMongock Annotation

  • Add your changeLog package path to your property file (application.yml). it's an array, so you can add more than one.

We are now going to create the first models of the project.

For this tutorial, we have an Employeemodel class in which the Department class is embedded.

Java
 
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
    @Id
    private String id;
  
    @NonNull
    private String code;

    private String name;
}


Java
 
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "employee")
public class Employee {

    @Id
    private String id;

    private String firstName;

    private String lastName;

    private String email;

    @NonNull
    private Department department;
}


For each model, we will create a Repository interface.

ChangeLogs and ChangeSets

ChangeLogs are migration classes. They contain ChangeSets, which are the methods that actually perform the migration.

To tell Mongock to run the migration, you need:

  1. Annotate the changeLog classes by @ChangeLog.
  2. Annotate the changeSet methods by @ChangeSet.

Let's create our first ChangeLog class to initialize the basic data.

Java
 
@ChangeLog(order = "001")
public class DatabaseInitChangeLog {


    @ChangeSet(order = "001", id = "init_departments", author = "aek")
    public void initDepartments(DepartmentRepository departmentRepository) {
        departmentRepository.save(Department.builder()
                .name("Human Resource Management")
                .code("HR")
                .build());
        departmentRepository.save(Department.builder()
                .name("R&D")
                .code("Research and Development (often abbreviated to R&D)")
                .build());
        departmentRepository.save(Department.builder()
                .name("Prod")
                .code("Production")
                .build());
    }

    @ChangeSet(order = "002", id = "init_Employee_HR", author = "aek")
    public void initHrEmployees(EmployeeRepository employeeRepository,
                              DepartmentRepository departmentRepository) {
        Optional<Department> hrDepartment = departmentRepository.findAllByCode("HR");

        if (hrDepartment.isPresent()){
            Employee employee1 = employeeRepository.save(Employee.builder()
                    .firstName("Dioms")
                    .lastName("Kane")
                    .email("[email protected]")
                    .department(hrDepartment.get())
                    .build());
            employeeRepository.save(employee1);

            Employee employee2 = employeeRepository.save(Employee.builder()
                    .firstName("Astrid")
                    .lastName("Flob")
                    .email("[email protected]")
                    .department(hrDepartment.get())
                    .build());
            employeeRepository.save(employee2);
        }
    }
    @ChangeSet(order = "003", id = "init_Employee_RAD", author = "aek")
    public void initRadEmployees(EmployeeRepository employeeRepository,
                              DepartmentRepository departmentRepository) {
        Optional<Department> radDepartment = departmentRepository.findAllByCode("R&D");

        if (radDepartment.isPresent()){
            Employee employee1 = employeeRepository.save(Employee.builder()
                    .firstName("Luis")
                    .lastName("Siruis")
                    .email("[email protected]")
                    .department(radDepartment.get())
                    .build());
            employeeRepository.save(employee1);
        }
    }


}


Mongock provides different ways of applying the ChangeSets. In our case, we are using the Spring Data Repository to save the data to a database. See the documentation for details.

Run the application and check the log which clearly shows us that the migration script is executed:

Migration Script is Executed


Suppose we want to add a new "salary" field to the Employee collection. It is important to update the data of existing documents.

After adding the field in Employee.java, create the Changelog class.

Java
 
@ChangeLog(order = "002")
public class DatabaseUpdateChangeLog {

    @ChangeSet(order = "002", id = "update_employees", author = "aek")
    public void updateEmployees(EmployeeRepository employeeRepository) {

        employeeRepository.findAll().forEach(employee -> {
            employee.setSalary(0.0);
            employeeRepository.save(employee);
        });
    }

}

And we're done.

In this post, we have learned how to manage and apply MongoDB database schema changes using Mongock.

Full source code can be found on GitHub. 


Spring Framework Data (computing) MongoDB Spring Data Spring Boot

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot Application With Spring REST and Spring Data MongoDB
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Introduction to Spring Boot and JDBCTemplate: Refactoring to SpringData JPA

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook