Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb - compound unique index using spring data not working

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.

enter image description here

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.

like image 847
G.S Avatar asked Sep 13 '25 08:09

G.S


1 Answers

As @Saxon mentioned:

Spring Data MongoDB 3.0, automatic index creation is turned off by default.

Instead of adding code, I am able to create the index by adding the spring data configuration in application.properties

spring.data.mongodb.auto-index-creation=true
like image 54
G.S Avatar answered Sep 15 '25 13:09

G.S