Last updated: 2024-10-04
Using Mongock in Spring Boot with Maven
Mongock is a library to describe and execute changes of the MongoDB database schema in changelogs. It's used for defining JSON schema, unique indexes and more. This article goes through the required setup of our Spring Boot application.
Basic configuration
To add Mongock to our application already using MongoDB, some changes are needed. 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 a custom database schema can be created. In the Professional plan, Mongock is available as an option to provide the required setup as well as the initial changelogs for all collections. By adding breakpoints, you can also generate changelogs for ongoing schema updates like document, field or relation changes.
See Pricing
or read quickstart