Trying to use $geoNear inside $lookup pipeline

In my aggregation pipeline I eventually get an array of store IDs, the next step is to run a lookup and get the stores documents but I need to limit them to a 10km max distance.

The problem I’m facing is that, for some reason, I get an error saying that “$geoNear is only valid as the first stage in a pipeline.”, even though it is the first stage in the $lookup pipeline.

Lookup stage:

{
  from: "stores",
  localField: "stores",
  foreignField: "_id",
  pipeline: [
    {
      $geoNear: {
        near: {
          type: "Point",
          coordinates: [0, 0]
        },
        distanceField: "distance",
        maxDistance: 10000
      }
    }
  ],
  as: "stores"
}

Not sure what I’m missing here.

MongoDB Version: 5.0.11

Found the problem!

It seems that when you use localField and foreignField in the lookup, they run similar to a first stage (like a $match). Removed them and moved all the logic to the pipeline.

{
  from: "stores",
  let: { ids: "$stores" },
  pipeline: [
    {
      $geoNear: {
        near: {
          type: "Point",
          coordinates: [0, 0]
        },
        distanceField: "distance",
        maxDistance: 10000,
        query: {
          $expr: {
            $in: ["$_id", "$$ids"]
          }
        }
      }
    }
  ],
  as: "stores"
}

Works like a charm :smile:

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