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




结构

{ "_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


posted @ 2017-12-21 13:43  thewindkee  阅读(119)  评论(0编辑  收藏  举报