DB.support = [
{
_id: ObjectId("12345"),
title: "Support",
instructions: [
{
image: "image-id-string-one"
},
{
image: "image-id-string-two"
},
{
image: "image-id-string-three"
},
]
}
]
DB.images = [
{
_id: ObjectId("11111111"),
id:"image-id-string-one",
image: "actual-image-one"
},
{
_id: ObjectId("222222222"),
id:"image-id-string-two",
image: "actual-image-two"
},
{
_id: ObjectId("333333333"),
id:"image-id-string-three",
image: "actual-image-three"
}
]
db.collection('support').aggregate([
{
"$match": {
"title": "Support"
}
},
// Let's say we match on title and expect only one record from above match
{
"$unwind": "$instructions"
},
{
"$lookup": {
"from": "images",
"localField": "instructions.image",
"foreignField": "id",
"as": "images"
}
},
{
"$unwind": "$images"
},
{
"$set": {
"instructions.image": "$images.image"
}
},
// Remove images array artifact from lookup from object.
{
"$unset": ["images"]
}
])
// So that the return object would look like this
{
_id: ObjectId("12345"),
title: "Support",
instructions: [
{
image: "actual-image-one"
},
{
image: "actual-image-two"
},
{
image: "actual-image-three"
},
]
}
// NOTE: I have tried so many ways to try to get to the above object but nothing.
First, you do not need to $unwind to $lookup as it is smart enough to lookup each element.
Since you want the result to be in instructions you might as well use it as the as of the lookup. The your $unset was on the right track to remove the lookup artifact. But I would opt for $map because I could specify all the fields I want rather than having to know which fields I do not want.
Lookup at this playground.
Next time you publish documents with _id, please make sure the _id is value. It is a pain to cut-n-paste in order to experiment with your data. With what you shared we get:
@Jake_Danforth, are you one of the few that looked at the playground I shared.
If it suits your requirement please mark my post as the solution. Otherwise, please share the reasons why it does not.
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.