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

时间:2017-12-18 02:45:30

标签: mongodb mongodb-query

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

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

我有以下索引

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

如果我基于lastName和firstName进行搜索,那么它的快速结果将在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 })

1 个答案:

答案 0 :(得分:0)

try use prefix on your regex to allow MongoDB use range

$arr = array_diff($cart_value_arr,$cart_remove_arr);

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