我有一个包含500万条记录的测试集: for(var i = 0; i< 5000000; i ++){db.testcol.insert({field1:i})}
插入索引: db.testcol.ensureIndex({FIELD1:1})
现在有趣的是:
mongos> db.testcol2.find({field1: {$gte: 0}},{field1:1,_id:0}).explain();
{
"cursor" : "BtreeCursor field1_1",
"isMultiKey" : false,
"n" : 5000000,
"nscannedObjects" : 0,
"nscanned" : 5000000,
"nscannedObjectsAllPlans" : 0,
"nscannedAllPlans" : 5000000,
"scanAndOrder" : false,
"indexOnly" : true,
"nYields" : 4,
"nChunkSkips" : 0,
"millis" : 4675,
"indexBounds" : {
"field1" : [
[
0,
1.7976931348623157e+308
]
]
},
"server" : "jvangaalen-PC:27020",
"millis" : 4675
}
Indexonly是真的,nscannedobject:0(意思是它从未查看真实文档来检查它
现在是相同的查询,但是_id:1(_id不在索引中,因此它也必须查看文档):
> db.testcol2.find({field1: {$gte: 0}},{field1:1,_id:1}).explain(); {
> "cursor" : "BtreeCursor field1_1",
> "isMultiKey" : false,
> "n" : 5000000,
> "nscannedObjects" : 5000000,
> "nscanned" : 5000000,
> "nscannedObjectsAllPlans" : 5000000,
> "nscannedAllPlans" : 5000000,
> "scanAndOrder" : false,
> "indexOnly" : false,
> "nYields" : 5,
> "nChunkSkips" : 0,
> "millis" : 3742,
> "indexBounds" : {
> "field1" : [
> [
> 0,
> 1.7976931348623157e+308
> ]
> ]
> },
> "server" : "jvangaalen-PC:27020",
> "millis" : 3742 }
响应时间从4.7秒降至3.7秒。 Indexonly:false和nscannedobjects是5000000(全部)。这看起来很有趣,因为它似乎必须为相同的结果集做更多的工作,但仍然要快得多。
这怎么可能?我尝试不同的原因是,当它运行一个indexonly时,我无法将nscannedobjects设置为0:分片后的真实查询