geoLocation or geoNear using let variables for coordinates and radius

26 Views Asked by At

I'm running an aggregate on my 'Users' collection to assign a list of cities that are within some radius of the users coordinates.

It seems that theres no way to assign let variables to the maxDistance field as this can only accept raw numbers.

Is there another way I can do the same kind of calculation not using $geoNear, or $geoWithin as both of these have the same limitations.

$lookup: {
  from: 'cities'
  let: {
    userCoordinates: '$coordinates',
    userSearchRadius: '$searchRadius'
  },
  pipeline: [
    {
      $geoNear: {
        near: {
          type: "Point",
          coordinates: '$$userCoordinates'
        },
        distanceField: 'distance',
        maxDistance: '$$userSearchRadius', // Issue here
        spherical: true,
      }
    }
  ],
  as: 'nearbyCities'
}
1

There are 1 best solutions below

0
ray On BEST ANSWER

A workaround to your issue would be adding a $match stage after the $geoNear stage on the calculated distance field.

db.users.aggregate([
  {
    $lookup: {
      from: "cities",
      let: {
        "userCoordinate": "$coordinate",
        "userSearchRadius": "$searchRadius"
      },
      as: "nearByCities",
      pipeline: [
        {
          $geoNear: {
            near: "$$userCoordinate",
            spherical: true,
            distanceField: "distance"
          }
        },
        {
          "$match": {
            $expr: {
              $lte: [
                "$distance",
                "$$userSearchRadius"
              ]
            }
          }
        }
      ]
    }
  },
  {
    $unwind: {
      path: "$nearByCities",
      preserveNullAndEmptyArrays: true
    }
  }
])

Mongo Playground