geoLocation 或 geoNear 使用 let 变量作为坐标和半径

问题描述 投票:0回答:1

我正在“用户”集合上运行聚合,以分配用户坐标一定半径内的城市列表。

似乎没有办法将 let 变量分配给

maxDistance
字段,因为它只能接受原始数字。

是否有另一种方法可以不使用

$geoNear
$geoWithin
进行相同类型的计算,因为这两种方法都有相同的限制。

$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'
}

对重复标志的响应:另一个集合上的 MongoDB $geoNear 聚合

这不适用,因为他们正在尝试使用 geoNear 使用 maxDistance 数字来查找最近的位置。

我问是否有使用 geoNear 和 geoLocation 的替代方法,因为我无法使用文档变量在 geoNear 中设置

maxDistance
。建议的链接不适用于我的问题。

mongodb mongodb-query aggregation-framework
1个回答
0
投票

解决您问题的方法是在计算的

$match
字段上的
$geoNear
阶段之后添加一个
distance
阶段。

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
    }
  }
])

蒙戈游乐场

© www.soinside.com 2019 - 2024. All rights reserved.