Mongodb,获取索引。零输入';键';

Mongodb,获取索引。零输入';键';,mongodb,indexing,Mongodb,Indexing,以下是mongodb shell中“getIndexes”命令的输出: db.users.getIndexes() [ { "v" : 1, "key" : { "online" : 1, "region" : 1, "status" : 0 }, &qu

以下是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”是什么意思? 在文档()中,只有“1”和“-1”

system.index.key

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


谢谢

我认为这是一种未定义的行为。从下面的例子来看,mongo确实会将索引值方向设置为0而感到困惑

简单测试: 递减指数

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

db.test.find.sort({t : 1}).explain()
使用的光标:
“光标”:“b光标t_1”

使用的光标:
“光标”:“b光标t\u 1反向”

这是预期的行为

上升指数 -

使用的光标:
“光标”:“b光标t_u1反向”

使用过的游标:
“游标”:“btreecursort_u1;-1”

这也是预期的行为

索引0 -

使用的光标:
“光标”:“b光标t\u 0反向”

使用的光标:
“光标”:“b光标t\u 0反向”

对于两个排序方向,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”的索引用于相等性测试,而不用于范围和排序。
db.test.ensureIndex({t : -1})
db.test.find.sort({t : 1}).explain()
db.test.find.sort({t : -1}).explain()
db.test.ensureIndex({t : 0})
db.test.find.sort({t : 1}).explain()
db.test.find.sort({t : -1}).explain()
{
        "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"
    }