MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

Mongodb $ lookup com documento aninhado


Você pode usar a agregação abaixo com mongodb 3.6 e acima
db.User.aggregate([
  { "$lookup": {
    "from": "orderTracking",
    "let": { "userId": "$userId" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$userId", "$$userId"] }}},
      { "$unwind": "$TrackLocation" },
      { "$lookup": {
        "from": "locationType",
        "let": { "location": "$TrackLocation.locationId" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": ["$locationId", "$$location"] }}}
        ],
        "as": "locationType"
      }},
      { "$project": {
        "_id": 0,
        "productTypeName": { "$arrayElemAt": ["$locationType.productTypeName", 0] },
        "at": "$TrackLocation.at"
      }}
    ],
    "as": "locationType"
  }},
  { "$replaceRoot": { "newRoot": { "$mergeObjects": ["$addres", "$$ROOT"] }}},
  { "$project": { "addres": 0 }}
])

Saída
[
  {
    "_id": ObjectId("59a504eb6171b554c02292a9"),
    "city": "Bengaluru",
    "country": "India",
    "dateOfBirth": "1992-01-01",
    "locationType": [
      {
        "at": "2017-10-11",
        "productTypeName": "Warehouse"
      },
      {
        "at": "2017-10-13",
        "productTypeName": "On Transit"
      }
    ],
    "state": "Karnataka",
    "userId": 12,
    "userName": "Shahabaz Shafi"
  }
]