【问题标题】:If mongodb aggregate does not use indexes for $lookup why does my performance increase when using indexes?如果 mongodb 聚合不使用 $lookup 的索引,为什么使用索引时我的性能会提高?
【发布时间】:2019-04-11 03:52:24
【问题描述】:

我有下面的代码 sn -p 来运行聚合命令。

      console.time("something");
      const cursor = await db.collection("main").aggregate([
        {
          $match: {
            mainField: mainField,
          },
        },
        {
          $lookup: {
            from: "reference",
            localField: "referenceId",
            foreignField: "referenceField",
            as: "something",
          },
        },
      ]);
      const results = await cursor.toArray();
      console.timeEnd("something");

我有一个便宜的云服务器用于测试目的(2gb ram,1 cpu 等),存储 mongodb。

我将 10k 文档插入主集合和参考集合(因此插入了 20k 文档)。

不使用索引并运行上述聚合查询需要 30 多秒才能返回结果。

如果我在参考集合上有以下索引并运行上述聚合查询,则结果大约需要 1.2 秒。

await db.collection("reference").createIndex({ referenceField: 1 });

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    不幸的是,MongoDB 手册目前没有提到 $lookup 的潜在索引使用情况,但情况确实如此。

    与您的示例类似的简单 $lookup 查询对另一个集合中的 foreignField 执行相等匹配,因此您添加了正确的索引以提高性能(假设该字段也具有合理的选择性)。

    在 MongoDB 4.0 中,$lookup 的索引使用情况未在 aggregation explain output 中报告。在 MongoDB 问题跟踪器中有一个相关问题需要关注/投票:SERVER-22622: Improve $lookup explain to indicate query plan on the "from" collection

    【讨论】:

    • 我创建了一个文档建议 (DOCS-10681) 来提及 MongoDB 3.4 中的索引使用情况,但它已在积压工作中停滞不前。 MongoDB 3.6 添加了more expressive $lookup features,因此现在可能的解释选项更加广泛。但是,至少应该在手册中提到使用索引的可能性,所以我将提交 PR 来改进这一点。
    猜你喜欢
    • 2020-03-05
    • 2018-02-06
    • 2014-11-25
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多