Search code examples
mongodbaggregate

Populate nested array objects using aggregate in mongodb


Im trying to populate the second nested array after using aggregate $lookup.

This is my original array.

 {
    "_id" : ObjectId("607da9c0c7cb26384c7810a6"), 
    "date" : ISODate("2021-04-20T00:00:00.000+0000"), 
    "clientID" : "601e6dc61766587af8ce76db", 
    "medications" : [
        {
            "_id" : ObjectId("6065de3aa95e721f587f7528")
        }, 
    ]
}
{
   from: "medications",
   localField: "medications._id",
   foreignField: "_id",
   as: "medications",
}

after using aggregate $lookup I get this result, but I still have nested array "inventory" that I need to populate. I tried adding another $lookup pipeline, but I don't know how the right way to do that.

{
    "_id" : ObjectId("607da9c0c7cb26384c7810a6"), 
    "date" : ISODate("2021-04-20T00:00:00.000+0000"), 
    "clientID" : "601e6dc61766587af8ce76db", 
    "medications" : {
        "_id" : ObjectId("6065de3aa95e721f587f7528"), 
        "medication": "med 1"
        "schedule": ["9am", "10pm"]
        "inventory":  "ObjectId("6076d55ab6aeb947dca85877")"
    }
}

This is the inventory item

{
   "_id" : ObjectId("6076d55ab6aeb947dca85877"), 
   "item": "Inventory item 1",
   "Qty": "10"
}

Expected Output

{
    "_id" : ObjectId("607da9c0c7cb26384c7810a6"), 
    "date" : ISODate("2021-04-20T00:00:00.000+0000"), 
    "clientID" : "601e6dc61766587af8ce76db", 
    "medications" : {
        "_id" : ObjectId("6065de3aa95e721f587f7528"), 
        "medication": "med 1"
        "schedule": ["9am", "10pm"]
        "inventory":  {
              "_id" : ObjectId("6076d55ab6aeb947dca85877"), 
              "item": "Inventory item 1",
              "Qty": "10"
         }
    }
}

Solution

  • You can try this one or alternatively use population.

    {
       from: "medications",
       localField: "medications._id",
       foreignField: "_id",
       as: "medications",
    }
    , {
      $unwind: {
        path: "$medications",
        preserveNullAndEmptyArrays: true
      }
    }, {
      $lookup: {
        from: "inventory",
        localField: "inventory._id",
        foreignField: "_id",
        as: "medications.inventory",
      }
    }
    

    You may check the $unwind in the official documentation. Just pay attention to the appropriate localField and foreignField.