MongoDB nested lookup with 3 levels

前端 未结 2 1419
粉色の甜心
粉色の甜心 2020-12-01 00:02

I need to retrieve the entire single object hierarchy from the database as a JSON. Actually the proposal about any other solution to achive this result would be highly appri

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 00:39

    With the mongodb 3.6 and above $lookup syntax it is quite simple to join nested fields without using $unwind.

    db.party.aggregate([
      { "$lookup": {
        "from": "address",
        "let": { "partyId": "$_id" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": ["$party_id", "$$partyId"] }}},
          { "$lookup": {
            "from": "addressComment",
            "let": { "addressId": "$_id" },
            "pipeline": [
              { "$match": { "$expr": { "$eq": ["$address_id", "$$addressId"] }}}
            ],
            "as": "address"
          }}
        ],
        "as": "address"
      }},
      { "$unwind": "$address" }
    ])
    

提交回复
热议问题