MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come popolare una matrice di ID profondamente nidificata dopo la ricerca aggregata in mongodb?

Prova questo:

db.A.aggregate([
    {
        $lookup: {
            from: "B",
            let: { refToA: "$_id" },
            pipeline: [
                {
                    $match: {
                        $expr: { $eq: ["$refToA", "$$refToA"] }
                    }
                },
                { $unwind: "$items" },
                { $unwind: "$items.options" },
                {
                    $lookup: {
                        from: "C",
                        localField: "items.options.codes",
                        foreignField: "_id",
                        as: "items.options.codes"
                    }
                },
                {
                    $group: {
                        _id: {
                            id: "$_id",
                            itemLabel: "$items.itemLabel"
                        },
                        labelB: { $first: "$labelB" },
                        refToA: { $first: "$refToA" },
                        items: {
                            $push: {
                                "itemLabel": "$items.itemLabel",
                                "options": "$items.options"
                            }
                        }
                    }
                },
                {
                    $group: {
                        _id: "$_id.id",
                        labelB: { $first: "$labelB" },
                        refToA: { $first: "$refToA" },
                        items: {
                            $push: {
                                itemLabel: "$_id.itemLabel",
                                "options": "$items.options"
                            }
                        }
                    }
                }
            ],
            as: "BCollection"
        }
    }
]);