MongoDB Aggregate Lookup and Unwind [duplicate]
Here is one solution - not sure just now if it's the prettiest possible but it certainly gets the job done:
db.transfers.aggregate([{ $lookup: { from: 'services', localField: 'requests.service', foreignField: '_id', as: 'requests2' }}, { $project: { "requests": { $map: { "input": { $zip: { "inputs": [ "$requests", "$requests2" ] } }, "as": "this", "in": { $mergeObjects: [ { $arrayElemAt: [ "$$this", 0 ] }, { "service": { $arrayElemAt: [ "$$this", 1 ] } } ] } } } }}])
The second option is to do this:
db.transfers.aggregate([{ $lookup: { from: 'services', localField: 'requests.service', foreignField: '_id', as: 'requests2' }}, { $project: { "requests": { $map: { "input": { $range: [ 0, { $size: "$requests2" } ] }, "as": "index", "in": { $mergeObjects: [ { $arrayElemAt: [ "$requests", "$$index" ] }, { "service": { $arrayElemAt: [ "$requests2", "$$index" ] } } ] } } } }}])
I've never actually compared the performance of the two verions but I would suspect the second is a little bit faster.