regex - MongoDB,通过正则表达式对索引字段的查询性能

标签 regex mongodb indexing mongodb-query

我想按名称查找帐户(在 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!'

MongoDB $regex

最佳答案

其实根据文档,

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/

相关文章:

javascript - javascript 缩小文件上的正则表达式最小匹配

JavaFX 在文本字段上按模式设置输入过滤器

MySQL 谓词推送

javascript - 保存 Mongoose 数据时出错

python - 为什么 `arr.take(idx)` 比 `arr[idx]` 快

python - 使用重复索引递增 Numpy 数组

php - 如何在 PHP 中获取 MySQL 函数的参数

c# - 用 C# 属性替换 XML 注释的正则表达式

mongodb - 无法导入mongodb

node.js - $lookup 聚合中的 $project