lookup配合pipline实现多层数组嵌套查询

db.division.aggregate([ //主表第一张表division
  {
    $lookup: {
      from: "teams", //第二张表teams
      let: {
    name:"$name" //前为第一张表的name字段,后为传到pipline中进行聚合连接的字段,相当于实参和形参
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [ //$xepr+$eq:传入的两个字段,前者为第二张表的name字段,后者为上面的$name字段即第一张表的
                "$name",
                "$$name"
              ]
            }
          }
        },
        {
          $lookup: {
            from: "players",
            let: {
              players: "$players"//将第二张表的players以$players名传入pipline
            },
            pipeline: [
              {
                $match: {
                  $expr: {
                    $in: [
                      "$_id",//获得第三章表的_id字段在$players中的结果
                      "$$players"
                    ]
                  }
                }
              },
              {
                $lookup: {//第三层嵌套为普通的lookup
                  from: "countries",
                  localField: "nationality",
                  foreignField: "_id",
                  as: "nationality"
                }
              }
            ],
            as: "players"//第二层嵌套中第二张表接收第三张表查询结果的字段
          }
        }
      ],
      as: "teams"//第一层嵌套中主表接收第二张表的字段,存在则覆盖,不存在则增加
    }
  }
])

 

posted @ 2022-08-19 15:05  忙碌了一整天的L师傅  阅读(234)  评论(0编辑  收藏  举报