zoukankan      html  css  js  c++  java
  • 使用稀疏索引来判断键是否存在




    结构

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


  • 相关阅读:
    linux 常用命令行
    二叉搜索树(BST)
    pytorch Gradient Clipping
    python 读写文件
    我终于可以毕业啦!
    为什么有可执行文件还需要库文件
    java常识
    *args、*kwargs
    win终端命令
    import_module
  • 原文地址:https://www.cnblogs.com/thewindkee/p/12873204.html
Copyright © 2011-2022 走看看