gregavola
gregavola

Reputation: 2539

MongoDB - Geospatial Index with Aggregation

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?

Upvotes: 2

Views: 1539

Answers (1)

grund
grund

Reputation: 351

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

Upvotes: 2

Related Questions