Mongodb 查询对于索引字段的部分字段搜索来说太慢了

标签 mongodb mongodb-query

我有以下包含 8 亿个文档的 mongodb 文档。

Customer
  {
   "lastName" : "LAST",
   "firstName" : "FIRST"
  }

我有以下索引

db.customer.createIndex( {lastName: 1, firstName: 1},{collation: { locale: "en_US", strength: 1}})

如果我根据姓氏和名字进行搜索,那么它会很快并在 10 毫秒内得到结果。

 db.customer.find({lastName:"LAST" ,firstName:"FIRST"}).collation({ locale: 'en_US', strength: 1 })

我正在尝试查找所有以“AS”作为姓氏字符的文档。但它需要 100 多秒才能返回响应。我尝试了以下选项,但都花费了 100 多秒。 mongoDB 是否真的像 sql 那样操作 ('%AS%')

1)

db.customer.find({lastName:{"$regex": "AS"} ,firstName:"FIRST"}).collation({ locale: 'en_US', strength: 1 })

2)

db.customer.find({lastName:{"$regex": "/AS/"} ,firstName:"FIRST"}).collation({ locale: 'en_US', strength: 1 })

3)

db.customer.find({lastName:{"$regex": "^/AS/"} ,firstName:"FIRST"}).collation({ locale: 'en_US', strength: 1 })

最佳答案

尝试在正则表达式上使用前缀以允许 MongoDB 使用范围

db.customer.find({lastName:{"$regex": "/^AS/"} ,firstName:"FIRST"}).collation({ locale: 'en_US', strength: 1 })

A regular expression is a “prefix expression” if it starts with a caret (^) or a left anchor (\A), followed by a string of simple symbols. For example, the regex /^abc./ will be optimized by matching only against the values from the index that start with abc. Additionally, while /^a/, /^a./, and /^a.$/ match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however, /^a./, and /^a.*$/ are slower. /^a/ can stop scanning after matching the prefix.

regex

关于Mongodb 查询对于索引字段的部分字段搜索来说太慢了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47861510/

相关文章:

python - pymongo DuplicateKeyError - 在 upsert 期间

node.js - 将数据从传感器推送到数据库

node.js - 在mongodb中使用多个条件更新数组

Node.js + mongoDB,mongojs $in 运算符出错

database - 在 $facet 中使用 $sort 和 $limit 时慢 Mongo 聚合

java - MongoDB 批量插入不适用于 java 驱动程序 2.11.2

java - Spring 数据蒙戈: upsert with various fields updated

python - mongodb findOne 和 $or 参数的顺序重要还是层次结构? [表现]

arrays - MongoDB 从对象数组中的数组中删除一个项目

c# - 驱动程序中缺少 MongoDB 驱动程序(查询生成器)?