-
I have a springboot application where am integrating mongock to add indices to the database. When I start the application, I see the below exception:
The mongo URL being used in the mongo template is The below is the change unit am trying to add: @ChangeUnit(id="addPartialIndexToCoaching", order = "0001", author = "user1")
@Slf4j
public class AddIndexToCoaching {
@Execution
public void addPartialIndexToCoaching(MongoTemplate mongoTemplate) {
// Create the index fields and sorting
Document indexFields = new Document()
.append("field1", 1)
.append("field2", 1)
.append("field3", 1);
// Define the partial filter expression using Criteria
Document partialFilterExpression = Criteria.where("status").is("DRAFT").getCriteriaObject();
// Create the IndexOptions with the partial filter expression
IndexOptions options = new IndexOptions().partialFilterExpression(partialFilterExpression);
// Create the index using MongoTemplate
mongoTemplate.getCollection("mycollection").createIndex(indexFields, options);
}
@RollbackExecution
@RollbackBeforeExecution
public void rollback() {
}
} My main app has the below enabled:
Am not sure what is wrong here. Any help is appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
This is probably happening because by default Mongock wraps the changeUnit within a transaction. However, MongoDB doesn't allow DDL operations within transactions. To fix, you can mark your changeUnit with @ChangeUnit(id="addPartialIndexToCoaching", order = "0001", author = "user1", transactional = false)
@Slf4j
public class AddIndexToCoaching {
@Execution
public void addPartialIndexToCoaching(MongoTemplate mongoTemplate) {
// Create the index fields and sorting
Document indexFields = new Document()
.append("field1", 1)
.append("field2", 1)
.append("field3", 1);
// Define the partial filter expression using Criteria
Document partialFilterExpression = Criteria.where("status").is("DRAFT").getCriteriaObject();
// Create the IndexOptions with the partial filter expression
IndexOptions options = new IndexOptions().partialFilterExpression(partialFilterExpression);
// Create the index using MongoTemplate
mongoTemplate.getCollection("mycollection").createIndex(indexFields, options);
}
@RollbackExecution
@RollbackBeforeExecution
public void rollback() {
}
} |
Beta Was this translation helpful? Give feedback.
This is probably happening because by default Mongock wraps the changeUnit within a transaction. However, MongoDB doesn't allow DDL operations within transactions.
To fix, you can mark your changeUnit with
transactional=false
, as follow: