I was trying to help in another post here : Lookup & populate objects in array. I have a working solution, but I wonder if we could do that with a single $lookup operation.
The array items we use to $lookup are objects themselves. It would not be a problem if we were just replacing the whole item, but we need to keep the original item (or parts of it at least) and insert the result back into it.
// user
{
"_id":1,
"cart":[
{"_id":2,"type":"A"},
{"_id":3,"type":"B"}
]
}
// items
[
{"_id":2,"name":"item 1"},
{"_id":3,"name":"item 2"}
]
// expected
{
"_id":1,
"cart":[
{"_id":2,"type":"A",item:{"_id":2,"name":"item 1"}},
{"_id":3,"type":"B",item:{"_id":3,"name":"item 2"}}
]
}
I used “let” and “pipeline” and wrote the following query but the “type” was not what I expected:
{
from: "items",
foreignField: "_id",
localField: "cart._id",
let:{type:"$cart.type"},
pipeline:[
{$project:
{
_id:1,
type:"$$type",
item:"$$ROOT"
}
}
],
as: "result"
}
here is the problem: instead of taking the value of the current item, “let” scans the whole array and extracts the “type” from all items, and sends this array to the pipeline: type:["A","B"]
.
Is there a simpler way than $unwind/$group, or without complex $match if that matters, that I missed?