📜  mongo db $lookup 遍历数据 - 任何代码示例

📅  最后修改于: 2022-03-11 15:00:11.254000             🧑  作者: Mango

代码示例1
db.parent.aggregate([
    { $match: { "_id": "5e6cd8c1996ddf1c28e14505" } },
    {
        $lookup: {
            from: "childnodes",
            let: { "child_id": "$parentList.child_id", "activeid": "$parentList.active_id" },
            pipeline: [
                { $match: { "$expr": { $eq: ["$_id", "$$child_id"] } } },
                {
                    $project: {
                        "child_id": "$_id",
                        "start_date": "$startDate",
                        "current_version_Key": "$active",
                        "active_child_name": {
                            "$reduce": {
                                "input": { "$objectToArray": "$$ROOT" },
                                "initialValue": "",
                                "in": {
                                    "$cond": [{ "$eq": ["$$this.k", "$$activeid"] },
                                        "$$this.v.childName",
                                        "$$value"
                                    ]
                                }
                            }
                        },
                        "text": {
                            "$reduce": {
                                "input": { "$objectToArray": "$$ROOT" },
                                "initialValue": "",
                                "in": {
                                    "$cond": [{ "$eq": ["$$this.k", "$$activeid"] },
                                        "$$this.v.text",
                                        "$$value"
                                    ]
                                }
                            }
                        },
                        "type": {
                            "$reduce": {
                                "input": { "$objectToArray": "$$ROOT" },
                                "initialValue": "",
                                "in": {
                                    "$cond": [{ "$eq": ["$$this.k", "$$activeid"] },
                                        "$$this.v.type",
                                        "$$value"
                                    ]
                                }
                            }
                        }
                    }
                }
            ],
            as: "finalList",
        },
    },
    {
        $project: {
          parentList: 0,
        },
      },
]);