首页 > 解决方案 > 在 mongoDB 中实现一个可以改进查询的索引

问题描述

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

*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。

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

标签: mongodbindexingmongodb-querymongodb-indexes

解决方案


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

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

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

然后,您可以使用$text查询运算符在索引中搜索精确匹配:

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

推荐阅读