【问题标题】:Implementing an index that would improve a query in mongoDB在 mongoDB 中实现一个可以改进查询的索引
【发布时间】:2020-06-28 01:37:26
【问题描述】:

我目前正在努力为我的查询实现索引。 这是原始查询:

*db.getCollection('products').aggregate([
    { $unwind: "$categories" },
    {  $unwind: "$categories"},
    {$group: {"_id": "$_id","title": {$first:"$title"},
            "asin":{$first:"$asin"},
            "categories": { $push: "$categories" }} },
    { $match: { "categories": { $in: ['T-Shirts']}} },
    { "$project":{ "_id": 0, "asin":1, "title":1  }  } ])*

这是我当前的索引代码:

*var cursor = 
db.products.explain("allPlansExecution").find(categories:{"T-Shirts"},{ categories:1, title:1, asin:1, _id:0,})
while (cursor.hasNext()) {
    print(cursor.next());
}*

当我运行索引代码时,我应该得到 nReturned 为 8,当前为 0。

有人可以指导我如何做到这一点吗?或者有人可以告诉我他们会添加什么吗?

【问题讨论】:

  • 我们可以看一个示例文档吗? $categories 需要解开两次吗?
  • 是的,因为“T-shirts”你只需要放松一次就找不到了”
  • 那么categories是一个数组数组?
  • 关于indexes。另外,发布一个示例文档,并说明您想要通过聚合实现什么。
  • 是的 category 是一个数组数组。

标签: mongodb indexing mongodb-query mongodb-indexes


【解决方案1】:

没有一种简单的方法可以索引另一个数组中包含的数组中的各个值。

在这种情况下,由于有问题的值是字符串,您可以使用文本索引,例如:

db.products.createIndex({"$**":"text"})

然后您可以使用$text 查询运算符来搜索索引以找到完全匹配:

db.products.find({$text:{$search:"\"T-Shirts\""}},{_id:0, asin:1, title:1})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    相关资源
    最近更新 更多