I have two collections (items, and subitems). The items collection has an object reference to subitems collection in subItems property (It's an array of subItem ObjectIds).
I want to build a query where I can first populate the subItems, and then filter based on populated field. I tried running the query below, but it seems that populate is ran last, therefore subItems[0].sharedGroups.groupId can never be filtered properly because it's not populated yet.
db.items.find({
$or: [
{ 'owner': 1 },
{ 'subItems[0].sharedGroups.groupId': { $in: [3691] } },
]
}).populate('subItems');
you should use $lookup and then $match in aggregation like this
db.items.aggregate([
{
$lookup:{
from:"subItems",
localField:"subItems", // field of reference to subItem
foreignField:"_id",
as :"subItems"
}},
{
$match:
{
$or: [
{ 'owner': 1 },
{ 'subItems.sharedGroups.groupId': { $in: [3691] } },
]
}
}]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With