I am trying to create unique compound index in mongodb using spring data.
But I see that the index is not created and the duplicate document is created in the DB.
My entity class:
@Document
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@CompoundIndexes(
@CompoundIndex(name = "daybook_index", def = "{'date' : 1, 'vehicleNumber' : 1}", unique = true)
)
public class Daybook {
private String date;
private String vehicleNumber;
private String unit;
}
I am using repository.insert()
method to create the document.
When I see in mongo express I see only one index created on _id
and the index defined in the entity class is not created.
Is it a bug in spring data or am I doing something wrong?
P.S.: I tried to delete the collection too before running the application but didn’t help.
2
Answers
As @Saxon mentioned:
Instead of adding code, I am able to create the index by adding the spring data configuration in
application.properties
As of Spring Data MongoDB 3.0, automatic index creation is turned off by default.
To turn it on you might use the proper flag overriding the method from MongoConfigurationSupport:
otherwise you might create the index with appropriate instructions.