查找操作缓慢

时间:2017-08-14 21:48:05

标签: mongodb aggregation-framework

我有以下查询:

query = [{
    $match: {
      $and: [{
        feed: {
          $in: feeds
        }
      }, {
        updatedAt: {
          $gte: new Date(date)
        }
      }
    ]
    }
  },
  {
    $lookup: {
      from: "feed",
      localField: "feed",
      foreignField: "_id",
      as: "feed"
    }
  },
  {
    $unwind: {
      path: "$feed",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $lookup: {
      from: "source",
      localField: "feed.source",
      foreignField: "_id",
      as: "feed.source",
    }
  },
  {
    $sort: {
      updatedAt: -1
    }
  },
  {
    $limit: limit
  },
  {
    $skip: skip
  }
];

查询耗时太长,大约需要10秒钟。

我读过https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/,但它仍然很慢。

我希望尽可能优化,有办法吗?该集合的索引为$ updatedAt:-1

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果您希望快速运行,我建议您删除$lookup管道阶段并根据其使用情况对文档进行建模。

但是,您可以在聚合查询的第一个匹配部分添加索引(updatedAt,feed)。但是你仍然会遇到这样的问题,即你仍在从另外两个不会使用任何索引的集合中查找。

  

$ match和$ sort管道运算符可以在管道开头出现时利用索引。

https://docs.mongodb.com/master/core/aggregation-pipeline/#pipeline-operators-and-indexes