使用 Zip Code 数据集进行聚合
在本页面
本文档中的示例使用zipcodes
集合。该系列可在以下网址获得:media.mongodb.org/zips.json。使用mongoimport将此数据集加载到mongod实例中。
数据模型
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
字段将位置保存为纬度经度对。
aggregate()方法
以下所有示例都使用mongo shell 中的aggregate()帮助程序。
aggregate()方法使用聚合管道将文档处理为聚合结果。 聚合管道由多个阶段组成,每个阶段在文档沿着管道传递时都会对其进行处理。文档按顺序通过各个阶段。
mongo shell 中的aggregate()方法在聚合数据库命令提供了一个包装器。有关用于数据聚合操作的更惯用的界面,请参阅驱动的文档。
返回人口超过 1000 万的国家
以下聚合操作将返回总人口超过 1000 万的所有州:
db.zipcodes.aggregate( [
{ $group: { _id: “$state“, totalPop: { $sum: “$pop“ } } },
{ $match: { totalPop: { $gte: 10*1000*1000 } } }
] )
在此 example 中,聚合管道包含$group阶段,后跟$match阶段:
此聚合操作的等效SQL是:
SELECT state, SUM(pop) AS totalPop
FROM zipcodes
GROUP BY state
HAVING totalPop >= (10*1000*1000)
[success] 也可以看看
按 State 返回平均城市人口
以下聚合操作返回每个 state 中城市的平均人口数:
db.zipcodes.aggregate( [
{ $group: { _id: { state: “$state“, city: “$city“ }, pop: { $sum: “$pop“ } } },
{ $group: { _id: “$_id.state“, avgCityPop: { $avg: “$pop“ } } }
] )
在这个 example 中,聚合管道包含$group阶段,后跟另一个$group阶段:
此聚合操作产生的文档类似于以下内容:
{
“_id“ : “MN“,
“avgCityPop“ : 5335
}
[success] 也可以看看
按 State 返回最大和最小城市
以下聚合操作按每个 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“ }
}
}
] )
在此 example 中,聚合管道包含$group阶段,$sort
阶段,另一个$group阶段和$project
阶段:
$sort阶段通过
pop
field value 对管道中的文档进行排序,从最小到最大; 即:通过增加 order。此操作不会更改文档。下一个$group阶段按
_id.state
字段(即:_id
文档中的state
字段)对 now-sorted 文档进行分组,并为每个 state 输出一个文档。该阶段还为每个 state 计算以下四个字段。使用$last表达式,$group operator 创建
biggestCity
和biggestPop
字段,用于存储人口和人口最多的城市。使用$first表达式,$group operator 创建smallestCity
和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。
译者:李冠飞
校对:李冠飞
最后更新于