一、@CompoundIndexes注解详解
@CompoundIndexes 是 org.springframework.data.mongodb.core.index 包的一个注解
作用是在程序启动的时候给数据库文档添加索引
这是一个复数数型式,所以可以配置多个索引,比如这样
@Document(collection = "mydb")
@CompoundIndexes({
@CompoundIndex(name = "name_1", def = "{'name':1}", unique = true),
@CompoundIndex(name = "timeSum.time_1_name_1", def = "{'timeSum.time':1,'name':1}")
})
其中,
@Document 标注数据库文档(表)
collection 标注文档名称(表名)
@CompoundIndex 标注 每个索引
name 索引的名称
def 索引的内容,json格式
unique 是否唯一,索引值唯一建,重复出现的记录仅保留一条,缺省默认false
组合(联合)索引写法
@CompoundIndex(name = "timeSum.time_1_name_1", def = "{'timeSum.time':1,'name':1}")
二、使用示例
@Document(collection = "mydb")
@CompoundIndexes({
@CompoundIndex(name = "name_1", def = "{'name':1}", unique = true),
@CompoundIndex(name = "timeSum.time_1_name_1", def = "{'timeSum.time':1,'name':1}")
})
public class Mydb {
private String id;
private String name;
}
三、@CompoundIndexes 不起作用,@CompoundIndexes没有创建索引的原因
一、必需加上 @Document 注解,单使用 @CompoundIndexes是没效果的
二、报错唯一键重复
Write failed with error code 11000 and error message 'E11000 duplicate key error collection
原因就是 目前的数据不能键唯一索引,解决办法是 去掉 unique = true