首页 > 解决方案 > MongoDB:查找后的操作需要很长时间

问题描述

我在使用大集合聚合 $lookup 时遇到速度问题。

这是两个请求。两者都包含在 $match 上。这个操作非常快。然后我做了一个 $lookup,这也很快。

之后,我对 $lookup 结果进行了操作。在第一种情况下,这个操作非常快,在第二种情况下,它非常慢。

第一个也是快速的请求:

db.getCollection('table1').aggregate([
    {
        "$match": {
            "type": "test",
        }
    },
    {
        "$lookup": {
            "from": "table2",
            "localField": "name",
            "foreignField": "name",
            "as": "lookup_names"
        }
    },
    {
        "$project": {
            "names": {
                // reduce on lookup_names is very fast
                "$reduce": {
                    "input": "$lookup_names",
                    "initialValue": ""
                    "in": {
                        "$concat": ["$$value.name", ".", "$$this.name"]
                    }
                }
            }
        }
    }
])

第二个缓慢的请求:

db.getCollection('table1').aggregate([
    {
        "$match": {
            "type": "test"
        }
    },
    {
        "$lookup": {
            "from": "table2",
            "localField": "name",
            "foreignField": "name",
            "as": "lookup_names"
        }
    },
    {
        // match on lookup_names is very slow
        "$match": {
            "lookup_names.name": "test"
        }
    }
])

有人能解释一下为什么第二个请求很慢吗?也许给我一个解决方案让它更快?

标签: mongodb

解决方案


推荐阅读