如何在MongoDB中合并$ lookup

时间:2019-04-05 13:49:05

标签: mongodb

我有3个类似这样的收藏集:

类型

{
   uuid : "uuid_type_1",
   info: "info sur le type 1"
}

{
   uuid : "uuid_piece_1",
   type_uuid : "uuid_type_1",
   info: "info sur la piece 1"
}

照片

{
   uuid : "uuid_photo_1",
   piece_uuid : "uuid_piece_1",
   info: "info photo 1"
}

我想加入这3个收藏集。

对于2,我成功进行了查找,对于3,我知道我必须使用管道,但是我尝试了这一点,但没有成功。

db("Essais").collection("TYPE").aggregate([
      {
            $match:recherche
      },
      {
            $lookup:{
                        from: "PIECE",
                        localField: "uuid",
                        foreignField : "type_uuid",
                        pipeline:[{
                              $lookup:{
                                    from: "PHOTO",
                                    localField: "uuid",
                                    foreignField : "piece_uuid",
                                    as: "PHOTOSPIECE"
                              }

                        }],
                        as: "PIECES"
            }
      }
)];

1 个答案:

答案 0 :(得分:0)

以下解决方案有效:

$lookup:
{
    from: "PIECE",
    let: { "uuidtype" : "$uuid" },
    pipeline:[
        { $match: { "$expr": { "$eq": [ "$type_uuid", "$$type_uuid" ] } } },
        {$lookup:
            {
                from: "PHOTO",
                as: "PHOTOSPIECE",
                let: { "uuidpiece" : "$uuid" },
                pipeline:[
                    { $match: { "$expr": { "$eq": [ "$piece_uuid", "$$uuidpiece" ] } }},

                ]
            }
        }
    ],
    as: "PIECES"
}