我想通过名称找到一个帐户(在MongoDB收集的50K帐户中)
以通常的方式:我们用字符串找到
db.accounts.find({ name: 'Jon Skeet' }) // indexes help improve performance!
正则表达式怎么样?这是一个昂贵的操作吗?
db.accounts.find( { name: /Jon Skeet/ }) // worry! how indexes work with regex?
编辑:
据WiredPrairie:
MongoDB使用RegEx的前缀来查找索引(例如:/^prefix.*/):
db.accounts.find( { name: /^Jon Skeet/ }) // indexes will help!'
其实根据文件,
原文链接:https://www.f2er.com/regex/357363.htmlIf an index exists for the field,then MongoDB matches the regular
expression against the values in the index,which can be faster than a
collection scan. Further optimization can occur if the regular
expression is a “prefix expression”,which means that all potential
matches start with the same string. This allows MongoDB to construct a
“range” from that prefix and only match against those values from the
index that fall within that range.
http://docs.mongodb.org/manual/reference/operator/query/regex/#index-use
换一种说法:
对于/ Jon Skeet / regex,mongo将完全扫描索引中的键,然后将获取匹配的文档,这可能比集合扫描更快。
对于/ ^ Jon Skeet / regex,mongo将仅扫描从索引中正则表达式开始的范围,这将更快。