使用稀疏索引来判断键是否存在




结构

{ "_id" : ObjectId("523b6e32fb408eea0eec2647"), "userid" : "newbie" }
{ "_id" : ObjectId("523b6e61fb408eea0eec2648"), "userid" : "abby", "score" : 82 }
{ "_id" : ObjectId("523b6e6ffb408eea0eec2649"), "userid" : "nina", "score" : 90 }

索引

db.scores.createIndex( { score: 1 } , { sparse: true } )

查询,走 score索引。

db.scores.find( { score: { $exists: true} } )


改成下面的查不出结果? 

需要改成 

db.scores.find( { score: { $exists: false}}).hint({'score':1})


上述$exists:true 查询,如果没有建立稀疏索引,而是非稀疏索引,那么会遍历所有的score索引 ,非常慢。


此外,如果是嵌套结构如: 'person.age', 在查询'person.age'是否存在的时候,先在person.age上建立 稀疏索引,然后

 db.scores.find( {'person.age':{$exists:true}}) 或者 db.scores.find( {'person.age':{$gt:0}})

如果此时仍需要查'person'是否存在, 也可以使用hint指定索引'person.age'。

 db.scores.find( {'person':{$exists:true}}).hint({'person.age':1})  


参考:https://docs.mongodb.com/v3.0/core/index-sparse/

https://stackoverflow.com/questions/8176310/can-mongodb-use-an-index-when-checking-for-existence-of-a-field-with-exists-ope


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值