Reputation: 9584
I have a collection of users that looks something like this:
{
"_id": ObjectId("54380a817a4b612a38e87613"),
"email": "[email protected]",
"ogp": [BIG NESTED COLLECTION... {}, {}, {}]
"created": ISODate("2012-02-28T23:10:07Z"),
"o_id": ObjectId("5438096f7a4b612a38e445f4")
"geo": {"country":"US", "city":"Seattle", "longitude": 123, "latitude":123}
}
I'd like to get all the users location and group them by country and total. Something like this:
[ {country:"US",total:250,000}, {country:"GB",total:150,000}, ... ]
Currently I'm just grabbing all of the documents and parsing it on the server:
db.users.find({'geo.country': {$ne: null},'geo.city': {$ne: null}}, {'geo.country':1}, function(err, doc) {
var data;
doc = _.groupBy(doc, function(par) { return par.geo.country; });
data = [];
return _.each(doc, function(item, key, obj) {
return data.push([key, obj[key].length]);
});
});
The problem with this is there are 600,000+ documents and the query takes about 1 minute to execute. Would the "aggregate" function would help speed up this query? If so how would I do it?
Upvotes: 2
Views: 176
Reputation: 85036
This should do it:
db.myCollection.aggregate([
{"$group": {_id: "$geo.country", count:{$sum:1}}}
])
Upvotes: 1