Last updated: 2022-11-28

  1. Learn
  2. Spring Data MongoDB
  3. Setup Mongock

Using Mongock in Spring Boot with Maven

Mongock is a library to describe and execute changes of the MongoDB database schema in changelogs. In this article we will describe the corresponding setup of our Spring Boot application.

Basic configuration

To add Mongock to our application from the introductory article, some changes are required. From Spring Boot 3 upwards only the following dependencies are required:

Extending our pom.xml for Spring Boot 3.0 and above

Up to Spring Boot 2.7 we need to add the mongock-bom in the depdencyManagement section of our pom.xml, as well as two more dependencies:

Extending our pom.xml up to Spring Boot 2.7

Our configuration class needs to be extended with the annotation @EnableMongock. Also, the following two properties are required.

The defined package is searched for changelogs to be picked up. The execution within transactions is recommended by Mongock and the required MongoTransactionManager has already been provided within the initial application. We explicitly leave out the setting auto-index-creation=true and create the unique indexes ourselves when needed.

JSON schema validation

With this setup, Mongock is already enabled and ready. Often the changelogs are used to create initial documents in MongoDB. However, at this point we want to create a collection together with a JSON schema so that the documents persisted later on meet our expectations.

Mongock Changelog creating a JSON schema and unique index

As of version 5 of Mongock, @ChangeLog has been replaced with @ChangeUnit. We initialize our collection in @BeforeExecution, since creating a collection inside the transaction of @Execution would not be allowed. After starting the application, the ChangeUnit is executed and the defined JSON schema has been added to MongoDB. To update the JSON schema of an existing collection, please check out this StackOverflow article.

Using Bootify, a Spring Boot application for MongoDB with any custom database schema can be created in the Free plan. In the Professional plan, Mongock is available as an option to generate the advanced setup as well as a basic JSON schema for the collections.

Learn more
or see pricing