在MongoDB地图中计算距离

在MongoDB地图中计算距离,mongodb,mapreduce,distance,Mongodb,Mapreduce,Distance,我有一个带有地理索引的MongoDB集合: > db.coll.getIndexes() [ // ... { "v" : 1, "key" : { "location" : "2dsphere" }, "ns" : "test.coll", "dropDups" : false, "name" : "location_2dsphere",

我有一个带有地理索引的MongoDB集合:

> db.coll.getIndexes()
[
    // ...
    {
        "v" : 1,
        "key" : {
            "location" : "2dsphere"
        },
        "ns" : "test.coll",
        "dropDups" : false,
        "name" : "location_2dsphere",
        "background" : false
    }
]

db.coll.findOne({location: {'$exists': true}}, {'location': 1})
{
    "_id" : ObjectId("52cd72ae2ac170aa3eaace6e"),
    "location" : [
        55.4545177559,
        11.5767419669
    ]
}
我在上面运行map reduce,它看起来像这样:

var map = function() {
     var value = 0;

     // ... various calculations on the value here

     var distance = 0; // < This is the problematic part
     if (distance < 1000) {
         val += distance;  // for example
     }

     emit(this._id, value)
}
var reduce = function(id, val) {
    return {id: val}
}

db.coll.mapReduce(map, reduce, {out: {inline: 1}})
find([-79,5], [40,20], 5);

返回每个文档的距离。但是我找不到一种方法将它与map reduce命令结合起来。

大圆公式就是一种方法

我在mongo和js中遇到了类似的问题。提出了这个函数。希望能有帮助

function find(point, latlng, radius){
       var dist = parseInt(radius) * 0.868976 / 60; // convert miles to rad

    if((point[0] <= latlng[0] + dist && point[1] >= latlng[1]- dist) 
    && (point[0] <= latlng[0]+ dist && point[1] >= latlng[1]- dist)){

        dx = latlng[0] - point[0];
        dy = latlng[1] - point[1];
        dx *= dx;
        dy *= dy;
        ds = dx + dy;
        rs = dist * dist;
        is =  ds <= rs;

        return is;
    }
}

我知道这是一个很晚才添加的功能,但是对于其他来到这里的人来说,了解一套可以执行地理相关功能的Javascript库可能会很好


另外,您已经尝试了什么?在纯js中这样做并不理想,因为mongo已经支持距离计算……至于“我尝试了什么”,我正在集合上运行
geonear
查询和map reduce。正在寻找一种将2结合起来的方法。@YuriPrezument您也可以在
mapReduce
中限定您正在尝试做的事情,而不仅仅是问“我可以使用它吗”,也许有人会建议“您正在尝试做什么”。到目前为止,我们还看不到这一点。请注意,您在投票名单上,所以您最好确定您想要的是什么。很好,谢谢!我已经用另一种方法解决了这个问题(而是用Python进行距离计算),但这似乎是一个很好的解决方案。
find([-79,5], [40,20], 5);