mongoose - MongoDB GeoNear Aggregate -
the question is:
consider following location: [-72, 42] , range (circle) of radius 2 around point. write query find states intersect range (circle). then, should return total population , number of cities each of these states. rank states based on number of cities.
i have written far:
db.zips.find({loc: {$near: [-72, 42], $maxdistance: 2}})
and sample output of is: { "city" : "woodstock", "loc" : [ -72.004027, 41.960218 ], "pop" : 5698, "state" : "ct", "_id" : "06281" }
in sql group "state", how able here while counting cities , total population?
assuming follow mongoimport routine zipcode data (i brought mine collection called zips7):
mongoimport --db mydb --collection zips7 --type json --file c:\users\drew\downloads\zips.json
or
mongoimport --db mydb --collection zips7 --type json --file /data/playdata/zips.json
(depending on os , paths)
then
db.zips7.ensureindex({loc:"2d"})
db.zips7.find({loc: {$near: [-72, 42], $maxdistance: 2}}).foreach(function(doc){ db.zips8.insert(doc); });
note db.zips7.stats() shows 30k rows , zips8 has 100 rows
db.zips8.aggregate( { $group : { _id : "$state", totalpop : { $sum : "$pop" }, town_count:{$sum:1} }} ) { "result" : [ { "_id" : "ri", "totalpop" : 39102, "town_count" : 10 }, { "_id" : "ma", "totalpop" : 469583, "town_count" : 56 }, { "_id" : "ct", "totalpop" : 182617, "town_count" : 34 } ], "ok" : 1 }
Comments
Post a Comment