我试图弄清楚_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" }
答案 0 :(得分:5)
由于属性_id
下的第一行cursor
,该解释确实能够反过来使用默认的BtreeCursor _id_ reverse
索引。 / p>
BtreeCursor
表示它是使用索引的游标,而_id_ reverse
表示它正在反向使用_id_
索引。
从所有意图和目的来看,它应该正确使用_id
索引。
另外,MongoDB还没有索引交集(https://jira.mongodb.org/browse/SERVER-3071),这意味着它仍然使用(对于大多数查询)条件和排序的单个索引,所以如果你想使用找到条件,你会发现你可能还需要在未来的索引中包含_id
。