-
-
Save jeffyuhaoliu/6559628 to your computer and use it in GitHub Desktop.
Node.js MongoDB HW#5.2 - Use aggregation framework calculate the average population of cities in California (abbreviation CA) and New York (NY) (taken together) with populations over 25,000. Note: To run this in Terminal, type in... mongo < [file name of this .js file]. This should run the command of the .js file you created with the mongo shell…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use hw5 | |
db.zips.aggregate([ | |
/* First group via sum up of the values of the cities with the same name | |
this is because a city will have multiple zips therefore, | |
multiple entries of cities with the same name */ | |
{ | |
$group: { | |
_id: { state: "$state", city: "$city"}, | |
pop: { $sum: "$pop" } | |
} | |
} | |
/* Match states "CT" and "NJ" */ | |
,{ | |
$match: { | |
$or: [{ "_id.state": "NY" },{ "_id.state": "CA" }] | |
// $or: [{ "_id.state": "CT" },{ "_id.state": "NJ" }] | |
} | |
} | |
/* Match cities with population greater than 25,000 */ | |
,{ | |
$match: { | |
pop: { $gt: 25000 }, | |
} | |
} | |
/* Average all the values of the previous match... Notice... grouping via | |
a non-existing value will group all of the values together */ | |
,{ | |
$group: { | |
_id: 0, | |
avgPop: { $avg: "$pop" } | |
} | |
} | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment