Reputation: 47
I know we have to unwind an array before using lookup but is there any way to unwind the array on the other document before performing the search? Right now I'm just getting the full array where the value is included.
As an alternative solution how would you go about filtering the full array so it only keeps the value I'm referencing on each document?
EDIT: As an example
COLLECTION AAA
{
array:[
{_id:01},
{_id:02}
]
}
COLLECTION BBB
{
array:[
{AAA_id:01},
{AAA_id:02}
]
}
In this example I would use this code to retrieve the linked values:
db.BBB.aggregate(
{$unwind: '$array'},
{
$lookup:
{
from: "AAA",
localField: "array.AAA_id",
foreignField: "array._id",
as: "linked"
}
}
)
But I would be getting something like this:
{
array:[
{AAA_id:01}
]
linked:[
{_id:01},
{_id:02}
]
}
{
array:[
{AAA_id:02}
]
linked:[
{_id:01},
{_id:02}
]
}
Instead of this:
{
array:[
{AAA_id:01}
]
linked:[
{_id:01}
]
}
{
array:[
{AAA_id:02}
]
linked:[
{_id:02}
]
}
Upvotes: 1
Views: 860
Reputation: 9473
$lookup retrieves full document with matching criteria. In this particular case to get rid of unneeded elements you could use $filter in $project pipeline, similar to this:
$project : {
_id : 1, //list all field here
linked: {
$filter : {
input : "$linked",
as : "item",
cond : {
$eq : ["$$item._id", "$$array.AAA_id"]
}
}
}
},
AFAIK there is no other way deal with that yet.
Upvotes: 2