MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Mongodb $lookup mit verschachteltem Dokument

Sie können die folgende Aggregation mit mongodb 3.6 verwenden und höher

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 }}
])

Ausgabe

[
  {
    "_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"
  }
]