2013-03-15 38 views
2

我试图找出是否按降序排列_id字段利用系统自动创建的索引。我试图用explain()来解决它,但我不确定。我应该在_id上创建一个额外的索引以降低数据返回速度?Mongo按降序排列_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" 
} 

回答

5

的解释的确给了一个很好的指标,因为它是能够使用的,因为财产cursor下的第一行的反向默认_id指数:BtreeCursor _id_ reverse

BtreeCursor显示它是使用索引的游标,而_id_ reverse显示它正在使用相反的_id_索引。

从所有意图和目的来看,它应该正确使用_id索引。作为额外的,MongoDB还没有索引相交(https://jira.mongodb.org/browse/SERVER-3071),这意味着它仍然使用(对于大多数查询)条件和排序的单个索引,所以如果你想使用查找条件会发现你可能需要在未来的索引中包含_id

+0

太好了。现在,如果我向名称字段添加索引并按_id按降序排序,它是否会利用_id上的索引或是否需要使用{name:1,_id:-1}创建新索引? – Glitches 2013-03-15 19:00:22

+0

@Glitches目前您需要制作复合索引 – Sammaye 2013-03-15 21:35:37