MongoDB-汇总的地理空间索引 [英] MongoDB - Geospatial Index with Aggregation

查看:42
本文介绍了MongoDB-汇总的地理空间索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从到文档中读到,不可能在MongoDB的聚合上使用地理空间索引.是否有替代方法?我试图运行查询以获取一定半径范围内的所有活动,然后按活动发生的次数对其进行分组/排序.有没有解决这个问题的方法?

I've read from the to docs that it is not possible to use a geospatial index on an aggregation with MongoDB. Is there an alternative to this? I am attempting to run a query take grab all activities within a certain radius, then group/sort them by the number of times that activity has occurred. Is there way around this issue?

推荐答案

您可以在地理查询中使用map-reduce.这是一个基于geo_mapreduce.js的示例(来自mongodb jstests):

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)
}

这篇关于MongoDB-汇总的地理空间索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆