【问题标题】:MongoDB aggregate slow with indexed match?MongoDB聚合速度慢与索引匹配?
【发布时间】:2020-03-12 21:11:16
【问题描述】:

我有一个集合 A 和一些字段 a,b,c,d...

如果我这样做:

db.A.aggregate([{$match: {a: true, b: false, c: false}, {$limit: 50}]) >> 这很快(0.1s)

如果我这样做了

db.A.aggregate(
        [
            {
                $lookup: {
                    from: 'B',
                    localField: 'b',
                    foreignField: '_id',
                    as: 'b'
                }
            },
            {$match: {'b.d': true}},
            { $limit: 50 }
        ]
    )

这大约需要 1.5s(文件很多,1.5s 我没问题)

现在,如果我像以前一样做,只是添加 $match(应该使用索引...):

db.A.aggregate(
        [
            {$match: {a: true, b: false, c: false}},
            {
                $lookup: {
                    from: 'B',
                    localField: 'b',
                    foreignField: '_id',
                    as: 'b'
                }
            },
            {$match: {'b.d': true}},
            { $limit: 50 }
        ]
    )

这需要 10 秒?我很困惑为什么。

PS:我对所有这些字段都有索引。

【问题讨论】:

    标签: mongodb aggregation-framework aggregate


    【解决方案1】:

    没关系,我发现了问题。我对除一个以外的所有字段都有索引,这降低了我的请求速度。

    我通过使用{explain: true} 选项找到了它,我看到它使用了一个不包含其中一个字段的复合索引。

    现在我的 1.5 秒查询已经很好了

    【讨论】:

      【解决方案2】:

      在您的情况下,这是最后一个 ($match, $lookup, $match),您正在使用 $match 阶段两次。在其他情况下,您将加入不同的集合,然后显示匹配的文档。 正如你所说,你有索引列,你能告诉我列的值是否包含文本、数字等。

      【讨论】:

      • 如果您共享示例数据,我将共享查询,这将提供比您更好的性能。
      • 我建议你在 mongoDB 官方网页上提问。链接:community.mongodb.com
      • 是的,但我需要 2 个匹配项,因为第二个匹配项是关于查找字段的
      • 你能分享数据样本,以便我对此进行查询。
      猜你喜欢
      • 1970-01-01
      • 2015-04-06
      • 2018-11-25
      • 1970-01-01
      • 2014-12-15
      • 2021-04-07
      • 1970-01-01
      • 2020-06-29
      • 2019-01-24
      相关资源
      最近更新 更多