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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With