计算MongoDB map-reduce中的距离

时间:2014-02-26 14:09:14

标签: mongodb mapreduce distance

我有一个带有地理索引的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}})

有没有办法在地图函数中计算location和点X之间的距离?

我正在寻找像$geoNear这样的东西,但不知何故与map-reduce相结合。

例如:

db.runCommand({geoNear: "coll", near: [-74, 40.74], spherical: true})

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

2 个答案:

答案 0 :(得分:4)

大圆公式是http://en.wikipedia.org/wiki/Great-circle_distance

的方法

我遇到了与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;
    }
}

我这样称呼:

find([-79,5], [40,20], 5);

答案 1 :(得分:1)

我知道这是一个后期添加,但对于其他人来到这里,了解一组可用于执行地理相关功能的Javascript库可能会很好。

https://github.com/manuelbieh/Geolib

相关问题