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

我想按名称查找帐户(在 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 将只扫描索引中以正则表达式开头的范围,这样会更快。

https://stackoverflow.com/questions/17501798/

相关文章:

php - 找不到类 'MongoClient'

mongodb - 图形数据库与文档数据库与三重存储

mongodb - 无法使用 --db 创建备份 mongodump。身份验证失败

mongodb - 在 MongoDB shell 查询中获取 "data from collect

c# - 序列化 Mongo ObjectId 时出现 JSON.NET 转换错误

mongodb - 如何使用 MongoDB 进行报告?

ruby - 获取 MongoDB 中列的最高值

python - 文档中的 Mongoengine creation_time 属性

regex - 如何使用 mongoose find 获取包含部分字符串的所有值?

mongodb - Mongoose - 在 ObjectId 数组上使用 Populate