【发布时间】:2017-02-07 11:10:16
【问题描述】:
我从 mongodb 文档那里听说
对于区分大小写的正则表达式查询,如果字段存在索引,则 MongoDB 会将正则表达式与索引中的值进行匹配,这可能比集合扫描更快。如果正则表达式是“前缀表达式”,则可以进行进一步优化,这意味着所有潜在匹配都以相同的字符串开头。这允许 MongoDB 从该前缀构造一个“范围”,并且只匹配索引中落在该范围内的那些值。
查询:
db.getCollection('contacts').find({username: {$regex: 'an'}}).explain()
这是没有索引的统计数据username
"cursor" : "BasicCursor",
"isMultiKey" : false,
"n" : 14234,
"nscannedObjects" : 107721,
"nscanned" : 107721,
"nscannedObjectsAllPlans" : 107721,
"nscannedAllPlans" : 107721,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 841,
"nChunkSkips" : 0,
"millis" : 108,
"server" : "random-ubunto:3001",
"filterSet" : false
以及带有索引的统计信息username
"cursor" : "BtreeCursor username_1",
"isMultiKey" : false,
"n" : 14234,
"nscannedObjects" : 14234,
"nscanned" : 106898,
"nscannedObjectsAllPlans" : 14234,
"nscannedAllPlans" : 106898,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 835,
"nChunkSkips" : 0,
"millis" : 142,
"indexBounds" : {
"username" : [
[
"",
{}
],
[
/an/,
/an/
]
]
},
"server" : "random-ubunto:3001",
"filterSet" : false
是的,我可以看到nscannedObjects 的不同之处。那很好,但问题是为什么索引的millis 比没有索引的要大。如果我们谈论性能,millis 应该反过来。目前
millis (Without Indexing) : 108
millis (With Indexing) : 142
【问题讨论】:
标签: mongodb performance search indexing