【问题标题】:Mongodb, getIndexes. Zero in 'key'MongoDB,getIndexes。 “钥匙”中的零
【发布时间】:2013-03-27 02:35:17
【问题描述】:

这是 mongodb shell 中“getIndexes”命令的输出:

db.users.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "online" : 1,
            "region" : 1,
            "status" : 0
        },
        "ns" : "Pr.users",
        "name" : "online_1_region_1_status_-1"
    },
    {
        "v" : 1,
        "key" : {
            "birthdate" : 1,
            "status" : 1,
            "region" : 1,
            "sex" : 1,
            "profile.uptime" : -1
        },
        "ns" : "Pr.users",
        "name" : "birthdate_1_status_1_region_1_sex_1_profile.uptime_-1"
    }
]

“键”值中的“0”是什么意思? 在文档 (http://docs.mongodb.org/manual/reference/method/db.collection.getIndexes/) 中只有“1”和“-1”。

system.indexes.key

包含一个文档,该文档包含索引中的键以及索引的顺序。索引可以是降序或升序。负值(例如 -1)表示按降序排序的索引,而正值(例如 1)表示按升序排序的索引。

谢谢!

【问题讨论】:

    标签: mongodb indexing


    【解决方案1】:

    我会说这是未定义的行为。从下面的示例来看,mongo 对设置为 0 的索引值方向感到非常困惑。

    简单测试:

    降序索引

    db.test.ensureIndex({t : 1})
    

    让我们看看在按字段“t”对测试集合进行排序时使用的游标

    db.test.find.sort({t : 1}).explain()
    

    使用的光标:"cursor" : "BtreeCursor t_1"

    db.test.find.sort({t : -1}).explain()
    

    使用的光标:"cursor" : "BtreeCursor t_1 reverse"

    这是预期的行为。

    升序索引

    db.test.ensureIndex({t : -1})
    

    -

    db.test.find.sort({t : 1}).explain()
    

    使用的光标:"cursor" : "BtreeCursor t_-1 reverse"

    db.test.find.sort({t : -1}).explain()
    

    使用的光标:"cursor" : "BtreeCursor t_-1"

    这也是预期的行为。

    索引 0

    db.test.ensureIndex({t : 0})
    

    -

    db.test.find.sort({t : 1}).explain()
    

    使用的光标:"cursor" : "BtreeCursor t_0 reverse"

    db.test.find.sort({t : -1}).explain()
    

    使用的光标:"cursor" : "BtreeCursor t_0 reverse"

    对于两个排序方向,mongo 都使用反向光标。

    不知道为什么 mongo 不处理这样的事情。即使是文档中的简单段落也足够了。

    有趣的是,你甚至可以将字符串设置为索引方向。

    {
            "v" : 1,
            "key" : {
                "t" : "sjdhfsdfsdf"
            },
            "ns" : "playground.test",
            "name" : "t_"
        }
    

    或者是这样的:

    db.test.ensureIndex({t: ObjectId()}, {additionalParam : "dfsdf"})
    ...
    {
            "v" : 1,
            "key" : {
                "t" : ObjectId("51527ebaa845a81ea8434d69")
            },
            "ns" : "playground.test",
            "name" : "t_",
            "additionalParam" : "dfsdf"
        }
    

    【讨论】:

    • 感谢您的研究!我已经测试了索引为零的字段搜索:db.test.find({t:50}).explain()。它使用该索引:“n”=“nscannedObjects”=“nscanned”=1。所以我猜带有“0”的索引用于相等测试,不用于范围和排序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    相关资源
    最近更新 更多