MongoDB - Geospatial Index with Aggregation

坚强是说给别人听的谎言 提交于 2019-12-03 21:03:44

You can use map-reduce on a geo query. Here is an example based on geo_mapreduce.js (from the mongodb jstests):

// setup test collection
var act_date = new Date(2010,06,07);
for (i = 1; i <= 10; i++) {
    db.activity.insert( { "geo" : { "lat" : 32.68331909, "long" : 69.41610718 }, "date":act_date, "activity" : 9 * i } );
    db.activity.insert( { "geo" : { "lat" : 35.01860809, "long" : 70.92027283 }, "date":act_date, "activity" : 3 } );
    db.activity.insert( { "geo" : { "lat" : 31.11639023, "long" : 64.19970703 }, "date":act_date, "activity" : 11 } );
    db.activity.insert( { "geo" : { "lat" : 32.64500046, "long" : 69.36251068 }, "date":act_date, "activity" : 9 } );
    db.activity.insert( { "geo" : { "lat" : 33.23638916, "long" : 69.81360626 }, "date":act_date, "activity" : 22 } );
    act_date.setDate(act_date.getDate() + 1);
}

db.activity.ensureIndex( { "geo" : "2d" } );
center = [ 32.68, 69.41 ];
radius = 10 / 111; // 10km; 1 arcdegree ~= 111km
geo_query = { geo : { '$within' : { '$center' : [ center, radius ] } } };

// map function
m = function() {
    emit( this.date, { "activity" : this.activity } );
};

// reduce function
r = function(key, values) {
    var total = 0;
    for ( var i = 0; i < values.length; i++ ) {
        total += values[i].activity;
    }
    return {"activity":total };
};

// mapreduce with geo query 
res = db.activity.mapReduce( m, r, { out : { inline : 1 }, query : geo_query } );
// sort results
res.results.sort(function(a, b){return b.value.activity - a.value.activity})
for (var i=0; i < res.results.length; i++) {
    print("Date: " + res.results[i]._id + " Activity: " 
                       + res.results[i].value.activity)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!