MongoDB @CompoundIndexes 不起作用,没效果;@CompoundIndexes的使用详细介绍

 

一、@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
 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cy谭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值