在MongoDB中合并两个$ lookup集合

时间:2018-08-22 08:39:15

标签: mongodb mongoose aggregation-framework

在这里,我尝试使用challenge从我的challengeusers集合中获取汇总结果,并且challengeusers具有user_id,并且我也使用$ lookup来加入用户。

使用此查询时,我得到以下输出。

"challenges": [
    {
        "_id": "5b7bf6fd87ec106308d7e3c1",
        "start_date": "2018-08-09T12:40:21.470Z",
        "end_date": "2018-08-05T12:40:21.470Z",
        "challnegedusers": [
            {
                "chalenge_id": "5b7bf6fd87ec106308d7e3c1",
                "user_id": "5b75623db457045e3bb12e0a",
                "status": 1
            },
            {
                "user_id": "5b75643c0a97791bcc9ed64c",
                "status": 1
            },
            {
                "user_id": "5b756144b457045e3bb12e08",
                "status": 1
            }
        ],
        "users": [
            {
                "_id": "5b756144b457045e3bb12e08",
                "first_name": "XYZ"
            },
            {
                "_id": "5b75623db457045e3bb12e0a",
                "first_name": "BAC"
            },
            {
                "_id": "5b75643c0a97791bcc9ed64c",
                "first_name": "YTA"
            }
        ]
    }
]

但是我希望challengeusersusers合并到一个对象中。

我最想让status中的challengeusers包含用户的信息。

预期输出:

"challenges": [
    {
        "_id": "5b7bf6fd87ec106308d7e3c1",
        "start_date": "2018-08-09T12:40:21.470Z",
        "end_date": "2018-08-05T12:40:21.470Z",
        "challnegedusers": [
            {
                "user_id": "5b75623db457045e3bb12e0a",
                "status": 1,
                "first_name": "BAC"
            },
            {
                "user_id": "5b75643c0a97791bcc9ed64c",
                "status": 1,
                "first_name": "YTA"
            },
            {
                "user_id": "5b756144b457045e3bb12e08",
                "status": 1,
                "first_name": "XYZ"
            }
        ]
    }
]

我正在使用的MongoDB聚合查询。

        let challenges = await ChallengeModel.aggregate([
            { $match: criteria },
            { $lookup: {
                from: 'challengeusers',
                localField: '_id',
                foreignField: 'challenge_id',
                as: 'challnegedusers'
            } },
            { $lookup: {
                    from: 'appusers',
                    localField: 'challnegedusers.user_id',
                    foreignField: '_id',
                    as: 'users'
            } },
            { $sort: {created_at: -1}}
        ]);

0 个答案:

没有答案