Zil_D
(Zil D)
April 11, 2022, 1:18pm
1
I’m using an aggeration query & if the first lookup has data then localField value will be taken from the first lookup data response and if that data is null then localField value will be _id.
Lookup 1:
aggregateQuery.push({
$lookup: {
from: "recentlyView",
pipeline: [
{
$match: {
$expr: {
$and: [{ $eq: ["$userId", req.user._id] }],
},
},
},
{
$sort: {
createdAt: -1,
},
},
{
$limit: 5,
},
],
as: "recentlyview",
},
});
aggregateQuery.push({
$unwind: {
path: "$recentlyview",
preserveNullAndEmptyArrays: true,
},
});
Zil_D
(Zil D)
April 11, 2022, 1:20pm
2
If recentlyView has data then lookup 2 should perform & if not then lookup 3 should add
Lookup 2:
aggregateQuery.push({
$lookup: {
from: "ResourcecarouselIteam",
localField: "recentlyview.resourceCarouselId",
foreignField: "carouselId",
as: "carouselDetails",
},
});
Lookup 3:
aggregateQuery.push({
$lookup: {
from: "ResourcecarouselIteam",
localField: "_id",
foreignField: "carouselId",
as: "carouselDetails",
},
});
The only change is value of localField.
steevej
(Steeve Juneau)
April 11, 2022, 1:46pm
3
I think you could simply add a $set stage after $unwind that sets the effective localField you want to use.
Something along the following untested lines:
{
'$set': {
effective_local_field: {
'$cond': { if: { '$eq': [ '$recentlyview.resourceCarouselId', null ] },
then: '$_id',
else: '$recentlyview.resourceCarouselId' }
}
}
}
and you do the following $lookup using localField : "effective_local_field" .
1 Like
Zil_D
(Zil D)
April 12, 2022, 1:56am
4
Thank you @steevej for your help.
1 Like
system
(system)
Closed
April 17, 2022, 1:56am
5
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.