MongoDB - Rewind an $unwind nested array after $lookup using $group MongoDB - Rewind an $unwind nested array after $lookup using $group mongodb mongodb

MongoDB - Rewind an $unwind nested array after $lookup using $group


Because the $lookup operator produces an array field, you need to $unwind the new field before the $group pipeline to get the desired result:

db.users.aggregate([    { "$unwind": "$profile" },    { "$unwind": {        "path": "$profile.universities",         "preserveNullAndEmptyArrays": true    } },     { "$lookup": {        "from": "universities",        "localField": "profile.universities._id",        "foreignField": "_id",        "as": "universities"    } },        { "$unwind": "$universities" },    { "$group": {        "_id": "$_id",        "emails": { "$first": "$emails" },        "profile": { "$first": "$profile" },        "universities": { "$push": "$universities" }    } },    { "$project": {        "emails": 1,          "profile.name" : 1,        "profile.company": 1,        "profile.title" : 1,        "profile.phone" : 1,        "profile.disabled": 1,                  "profile.universities": "$universities"    } }]).pretty()