【问题标题】:how to get distance using $within $centerSphere如何使用 $within $centerSphere 获取距离
【发布时间】:2014-09-29 22:03:02
【问题描述】:

我正在使用$within$centerSphere 仅获取具有一定半径的圆圈内的集合文档。

我使用的查询是:

{"value.pos":{"$within":{"$centerSphere":
[[40.6861735,14.777354800000012],0.0007839325190887568]}}}

其中0.0007839325190887568 = 5 * 6378.1(地球半径)。

我需要的是显示点与文档元素位置之间的距离。

我正在为 nodejs 使用 mongodb 驱动程序。

收到距离后,我只需要以编程方式订购结果,而且只有用户想要它。

我不能使用 mongoose,因为我需要更改太多现有代码,所以我想使用标准 mongodb 驱动程序。

有解决办法吗?

谢谢!

【问题讨论】:

    标签: node.js mongodb geospatial


    【解决方案1】:

    $within 自 2.4 起已被弃用。做你想做的事,确保你至少运行 MongoDB 2.4 并在聚合管道阶段使用geoNear。需要使用聚合来获得结果中的距离。

    db.places.aggregate([
        {
            $geoNear: {
                near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
                distanceField: "distance",
                maxDistance: < your distance in meters>,
                spherical: true
            }
        }
    ])
    

    确保您在 value.pos 上有一个 2dsphere 索引。

    【讨论】:

      猜你喜欢
      • 2012-03-06
      • 2022-06-15
      • 1970-01-01
      • 2011-05-28
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多