Mongo按降序排序_id是否利用自动索引或?

Gli*_*hes 3 mongodb

我试图弄清楚_id字段按降序排序是否利用了系统自动创建的索引.我试着用explain()来搞清楚,但我不确定.我应该按降序在_id上创建一个额外的索引,以便更快地恢复数据吗?

> db.foo.insert({ name: 'foo' });
> db.foo.insert({ name: 'bar' });
> db.foo.find();
{ "_id" : ObjectId("5142d30ca4a8b347cb678c1a"), "name" : "foo" }
{ "_id" : ObjectId("5142d310a4a8b347cb678c1b"), "name" : "bar" }
> db.foo.find().sort({ _id: -1 });
{ "_id" : ObjectId("5142d310a4a8b347cb678c1b"), "name" : "bar" }
{ "_id" : ObjectId("5142d30ca4a8b347cb678c1a"), "name" : "foo" }
> db.foo.find().sort({ _id: -1 }).explain();
{
    "cursor" : "BtreeCursor _id_ reverse",
    "isMultiKey" : false,
    "n" : 2,
    "nscannedObjects" : 2,
    "nscanned" : 2,
    "nscannedObjectsAllPlans" : 2,
    "nscannedAllPlans" : 2,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "indexBounds" : {
        "_id" : [
            [
                {
                    "$maxElement" : 1
                },
                {
                    "$minElement" : 1
                }
            ]
        ]
    },
    "server" : "localhost:27017"
}

Sam*_*aye 5

_id由于属性下面的第一行,解释确实给出了一个很好的指标,表明它是否能够反向使用默认索引cursor:BtreeCursor _id_ reverse.

BtreeCursor表明它是一个使用索引的游标,同时_id_ reverse表明它正在_id_反向使用索引.

从所有意图和目的来看,它应该_id正确地使用索引.

另外,MongoDB还没有索引交集(https://jira.mongodb.org/browse/SERVER-3071),这意味着它仍然使用(对于大多数查询)条件和排序的单个索引因此,如果您希望使用查找条件,您会发现您可能还需要包含_id将来的索引.