如何在$ centerSphere中使用$来获得距离

时间:2014-09-29 22:03:03

标签: node.js mongodb geospatial

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

我使用的查询是:

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

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

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

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

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

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

有解决方案吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

$ 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索引。