我们目前正在使用一个名为items的集合,该集合在MongoDB数据库中包含1000万个条目。
此集合包含(除许多其他外)两个名为titlecountry_code的列。一个这样的条目看起来像这样

{
  "_id": ObjectId("566acf868fdd29578f35e8db"),
  "feed": ObjectId("566562f78fdd2933aac85b42"),
  "category": "Mobiles & Tablets",
  "title": "360DSC Crystal Clear Transparent Ultra Slim Shockproof TPU Case for Iphone 5 5S (Transparent Pink)",
  "URL": "http://www.lazada.co.id/60dsc-crystal-clear-transparent-ultra-slim-shockproof-tpu-case-for-iphone-5-5s-transparent-pink-3235992.html",
  "created_at": ISODate("2015-12-11T13:28:38.470Z"),
  "barcode": "36834ELAA1XCWOANID-3563358",
  "updated_at": ISODate("2015-12-11T13:28:38.470Z"),
  "country_code": "ID",
  "picture-url": "http://id-live.slatic.net/p/image-2995323-1-product.jpg",
  "price": "41000.00"
}

country_code上的基数很高。我们为这些列创建了两个文本索引:
db.items.createIndex({title: "text", country_code: "text"})

在我们的示例中,我们试图查询:
db.items.find({"title": { "$regex": "iphone", "$options": "i" }, country_code: "US"}).limit(10)

一个大约需要6秒才能完成的查询,对于这种类型的数据库来说,这似乎异常高。
每当我们尝试结果较少的country_code(例如,country_code:“uk”)时,它将在毫秒内返回结果。
有没有什么特别的原因,为什么这些查询在返回结果的时间上有如此大的差异?
编辑:
这里的所有答案都有帮助,所以如果你自己有这个问题,请尝试所有3种解决方案。但只能将1标记为正确。

最佳答案

切换索引中字段的顺序。秩序很重要。

db.items.createIndex({country_code: "text", title: "text"})

查询时请确保维护此订单:
db.items.find({country_code: "US", "title": { "$regex": "iphone", "$options": "i" }}).limit(10)

这样做的目的是大大减少需要的title字段的数量,以便搜索子字符串。
正如@jaco所提到的,您应该利用您的“文本”索引。见how to query a text index here

10-08 04:47