0

我有 2 个收藏:

users收藏:

{
    "_id": "1234141341"
    "name": "David",
    "is_active": True,
    "age": 20
}

locations收藏:

{
    "owner": "1234141341"
    "type": "Point"
    "coordinates": [ 105.843111, 21.045752 ]
}

我想加入users收藏与locations收藏。我的查询:

db.collection.aggregrate(
    {
        "$match": {
            "is_active": True,
        }
    },
    {
        "$lookup": {
            "from": "locations",
            "as": "location",
            "let": {"user_id": "$_id", "list_user_id": "the expression to get list of user id after $match stage"},
            "pipeline": [
                { 
                    "$geoNear": {
                        "near": {"type": "Point", "coordinates": [ 105.843111, 21.045752 ]},
                        "distanceField": "distance",
                        "query": {
                            // "owner": {"$in": "$$list_user_id"}      // <---- filter location that belong filtered user here
                        },
                    }
                },
                {
                    "$redact": {
                        "$cond": {
                            "if": {"$lte": ["$distance", 10000000000]},
                            "then": "$$KEEP",
                            "else": "$$PRUNE",
                        }
                    }
                },
                {
                    "$match": {
                        "$expr": {"$eq": ["$owner", "$$user_id"]},
                    },
                },
            ],
        }
    }
)

为了优化这个聚合查询,我想在 stage 之后获取用户 id 列表$match,然后将此用户 id 列表传递到属于过滤用户的过滤器位置$geoNear的阶段。$lookup所以这个$geoNear阶段不会计算所有的位置。我已经阅读了 mongo 文档,也阅读了这个站点中的问题,但我找不到答案。对此的任何想法表示赞赏,谢谢

4

1 回答 1

0

通常,当您想在要查找的集合中进行过滤时,您可以:

{"$match": {
 "$expr": { "$in": [ "$owner", "$$user_id" ] }
}}

您可以$match在开头添加一个阶段,或者我相信您可以将整个$expr表达式放入查询中。

于 2020-05-22T06:21:38.470 回答