This question has previously been marked as a duplicate of this question I can with certainty confirm that it is not.
This is not a duplicate of the linked question because the elements in question are not an array but embedded in individual objects of an array as fields. I am fully aware of how the query in the linked question should work, however that scenario is different from mine.
I have a question regarding the $lookup query of MongoDb. My data structure looks as follows:
My "Event" collection contains this single document:
{
"_id": ObjectId("mongodbobjectid..."),
"name": "Some Event",
"attendees": [
{
"type": 1,
"status": 2,
"contact": ObjectId("mongodbobjectidHEX1")
},
{
"type": 7,
"status": 4,
"contact": ObjectId("mongodbobjectidHEX2")
}
]
}
My "Contact" collection contains these documents:
{
"_id": ObjectId("mongodbobjectidHEX1"),
"name": "John Doe",
"age": 35
},
{
"_id": ObjectId("mongodbobjectidHEX2"),
"name": "Peter Pan",
"age": 60
}
What I want to do is perform an aggregate query with the $lookup operator on the "Event" collection and get the following result with full "contact" data:
{
"_id": ObjectId("mongodbobjectid..."),
"name": "Some Event",
"attendees": [
{
"type": 1,
"status": 2,
"contact": {
"_id": ObjectId("mongodbobjectidHEX1"),
"name": "John Doe",
"age": 35
}
},
{
"type": 7,
"status": 4,
"contact": {
"_id": ObjectId("mongodbobjectidHEX2"),
"name": "Peter Pan",
"age": 60
}
}
]
}
I have done the same with single elements of "Contact" referenced in another document but never when embedded in an array. I am unsure of which pipeline arguments to pass to get the above shown result?
I also want to add a $match query to the pipeline to filter the data, but that is not really part of my question.
$unwindpipeline to flatten the array of embedded documents for you to apply the$lookupoperator on the "attendees.contact" field and then after the$lookup, pipe another$unwindand$groupthe resulting docs to get your desired output. The other answer also applies if you are using the upcoming MongoDB 3.4{"$unwind": "$attendees"}, then{ "$lookup" : {"from" : "Contact", "localField" : "attendees.contact","foreignField": "_id", "as" : "contactlist" }}, then{"$unwind": "$contactlist"}and then$group?db.event.aggregate([ { "$unwind": "$attendees" } ]);, check the result to see if the attendees array is deconstructed properly, add the next pipeline stagedb.event.aggregate([ { "$unwind": "$attendees" },{ "$lookup" : {"from" : "Contact", "localField" : "attendees.contact","foreignField": "_id", "as" : "contactlist" }} ]);, run that and repeat the steps till you get to the final pipeline step.