使用 Zip Code 数据集进行聚合
在本页面
zipcodes
集合中的每个文档都具有以下形式:{
"_id": "10280",
"city": "NEW YORK",
"state": "NY",
"pop": 5574,
"loc": [
-74.016323,
40.710537
]
}
_id
字段将 zip code 保存为 string。city
字段包含 city name。一个城市可以有多个与之关联的 zip code,因为城市的不同部分可以各自具有不同的 zip code。state
字段包含两个字母 state 缩写。pop
字段包含人口。loc
字段将位置保存为纬度经度对。
以下聚合操作将返回总人口超过 1000 万的所有州:
db.zipcodes.aggregate( [
{ $group: { _id: “$state“, totalPop: { $sum: “$pop“ } } },
{ $match: { totalPop: { $gte: 10*1000*1000 } } }
] )
SELECT state, SUM(pop) AS totalPop
FROM zipcodes
GROUP BY state
HAVING totalPop >= (10*1000*1000)
以下聚合操作返回每个 state 中城市的平均人口数:
db.zipcodes.aggregate( [
{ $group: { _id: { state: “$state“, city: “$city“ }, pop: { $sum: “$pop“ } } },
{ $group: { _id: “$_id.state“, avgCityPop: { $avg: “$pop“ } } }
] )
此聚合操作产生的文档类似于以下内容:
{
“_id“ : “MN“,
“avgCityPop“ : 5335
}
以下聚合操作按每个 state 的填充返回最小和最大的城市:
db.zipcodes.aggregate( [
{
$group:{
_id: { state: “$state“, city: “$city“ },
pop: { $sum: “$pop“ }
}
},
{ $sort: { pop: 1 } },
{
$group:{
_id : “$_id.state“,
biggestCity: { $last: “$_id.city“ },
biggestPop: { $last: “$pop“ },
smallestCity: { $first: “$_id.city“ },
smallestPop: { $first: “$pop“ }
}
},
// the following $project is optional, and
// modifies the output format.
{
$project:{
_id: 0,
state: “$_id“,
biggestCity: { name: “$biggestCity“, pop: “$biggestPop“ },
smallestCity: { name: “$smallestCity“, pop: “$smallestPop“ }
}
}
] )
- 在管道的这个阶段,文件类似于以下内容:{“_id“ : “WA“,“biggestCity“ : “SEATTLE“,“biggestPop“ : 520096,“smallestCity“ : “BENGE“,“smallestPop“ : 2}
- 最后的$project阶段将
_id
字段重命名为state
,并将biggestCity
,biggestPop
,smallestCity
和smallestPop
移动到biggestCity
和smallestCity
嵌入文档中。
此聚合操作的输出文档类似于以下内容:
{
“state“ : “RI“,
“biggestCity“ : {
“name“ : “CRANSTON“,
“pop“ : 176404
},
“smallestCity“ : {
“name“ : “CLAYVILLE“,
“pop“ : 45
}
}
[1] | 一个城市可以有多个与之关联的 zip code,因为城市的不同部分可以各自具有不同的 zip code。 |
译者:李冠飞
校对:李冠飞
最近更新 1yr ago