Any way to conditionally add localField in lookup?

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,
  },
});

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.

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

Thank you @steevej for your help.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.