我有下面的类作为我的文档。
@Data
@Builder
@Document(collection = "test")
public class TestData {
@Id
private String id;
private String name;
@Indexed(unique = true)
private String hash;
}
即使我使用的是启用了唯一性的Indexed,我也可以将重复的文档插入到集合中。但如果我在mongoshell中生成索引,那么它就可以工作了。
有什么方法可以让我只通过代码指定唯一的索引吗?
这就是复合索引在我的代码中的使用方式
@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();
}
请在spring-boot应用程序的application.properties文件中使用以下代码,它将工作。
spring.data.mongodb.auto-index-creation: true
谢谢
如果你有一个配置组件,你应该覆盖autoIndexCreation方法,如下所示:
@Configuration
public class MongoConfiguration extends AbstractMongoClientConfiguration
{
@Override
protected boolean autoIndexCreation() {
return true;
}}