MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Mongodb $ ricerca con documento nidificato

Puoi utilizzare l'aggregazione di seguito con mongodb 3.6 e oltre

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

Risultato

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