- • Quickstart
- • Documentation
- • Documentation DevOps
- • Spring Data
- › MongoDB
- • Spring REST
- • IntelliJ Integration
Last updated: 2022-03-20
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.
To add Mongock to our application from the introductory article, we need to add the
mongock-bom in the
depdencyManagement section of our
pom.xml. Also, two more dependencies are required to use Mongock in our Spring Boot Maven context.
Extending our pom.xml for Mongock
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.