我想按名称查找帐户(在 50K 帐户的 MongoDB 集合中)
以通常的方式:我们用字符串查找
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 来查找索引(例如:/^prefix.*/
):
db.accounts.find( { name: /^Jon Skeet/ }) // indexes will help!'
最佳答案
其实根据文档,
If 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/
正则表达式,mongo 会完整扫描索引中的键,然后会获取匹配的文档,这可能比集合扫描更快。
对于 /^Jon Skeet/
正则表达式,mongo 将只扫描索引中以正则表达式开头的范围,这样会更快。
关于regex - MongoDB,通过正则表达式对索引字段的查询性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17501798/