Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot mongo db index (unique=true) not working

I have the below class as my document.

@Data
@Builder
@Document(collection = "test")
public class TestData {
    @Id
    private String id;

    private String name;

    @Indexed(unique = true)
    private String hash;

}

Even if I'm using Indexed with unique enabled, I'm able to insert duplicate documents into collection. But if I generate index in mongo shell then it is working.

Is there any way where I can specify unique Index through code only?

like image 338
Sumedha Avatar asked Nov 15 '22 08:11

Sumedha


1 Answers

This is how the compound index is used in my code

@Getter
@Setter
@Document
@CompoundIndexes({
@CompoundIndex(name = "name_author_idx", def = "{'name' : 1, 'author' : 1}", unique = true, background = true)})
public class Book implements Transformer {

    @Id
    private String id;

    @Field(name = "name")
    private String name;

    @Field(name = "author")
    private String author;

    @Field(name = "qty")
    private Integer qty;

    @Field(name = "price")
    private Double price;

    @Field(name = "created_time")
    private LocalDateTime createdTime = LocalDateTime.now();
}
like image 56
Rajitha Bhanuka Avatar answered Jan 16 '23 01:01

Rajitha Bhanuka