arrays - MongoDB | 列出纽约每个城市的邮政编码/邮政编码
问题描述
作为我个人项目的一部分,我正在学习如何编写 MongoDB 查询。我想我遗漏了一些小东西或大东西(我不知道),并希望有人能指出我的 MongoDB 查询出了什么问题。我正在研究 MongoDB 上提供的流行邮政编码数据集:https ://docs.mongodb.com/manual/tutorial/aggregation-zip-code-data-set/
zipcodes 集合中的文档示例具有以下形式:
{
"_id": "10280",
"city": "NEW YORK",
"state": "NY",
"pop": 5574,
"loc": [
-74.016323,
40.710537
]
}
目标:我正在尝试查找纽约州 (NY) 每个城市的人口,其中的结果列出了每个城市中包含的邮政编码。输出应如下所示:
{
_id : "ELMIRA",
population : <population of ELMIRA>,
postal_codes : [
<PostalCode1 in ELMIRE>,
<PostalCode2 in ELMIRE>,
<PostalCode3 in ELMIRA>
]
},
{
_id : "WHITESVILLE",
population : <population of WHITESVILLE>,
postal_codes : [
<PostalCode1 in WHITESVILLE>
]
},
我的代码:这是我到目前为止所写的
db.getCollection('codes').aggregate([
{
$group: {
_id: {city: "$city", state:"$state"},
population: {$sum: "$pop"},
postal_codes: {$addToSet: "$_id"}
}
},
{
$match: {
"_id.state":"NY"
}
},
{
$group: {
_id: "$_id.city",
population: {$last: "$population"},
postal_codes: {$last: "$postal_codes"}
}
}
])
问题- 我在代码中看到的问题是,它只列出了纽约一个有多个邮政编码的城市的邮政编码,如下所示。在美国,一个城市可能会重叠多个邮政编码。如何修复我的查询以包含纽约每个城市的所有邮政编码而不是其中一个?
{
"_id" : "OSSINING",
"population" : NumberInt(29926),
"postal_codes" : [
"10562"
]
}
{
"_id" : "COLD SPRING",
"population" : NumberInt(4904),
"postal_codes" : [
"10516"
]
}
{
"_id" : "NORTH WOODMERE",
"population" : NumberInt(19582),
"postal_codes" : [
"11581"
]
}
解决方案
您可以简单地使用$addToset
而不是$last
获取所有postal_codes
.
$match
附带说明:您可以通过将中间结果集推到state
较早阶段来减少中间结果集,从而使您的代码更具性能。
db.collection.aggregate([
{
$match: {
"state": "NY"
}
},
{
$group: {
_id: "$city",
population: {
$sum: "$pop"
},
postal_codes: {
$addToSet: "$_id"
}
}
}
])
这是Mongo游乐场供您参考。
推荐阅读
- python - 如何将标签的文本值设置为 .kv 文件中的全局变量?
- c# - 如何允许点击透明 WinForm OpenGL 覆盖
- jupyter-notebook - 如何将 Apache Drill 集成到 Jupyter Notebook
- javascript - 单击指向新页面的链接后如何运行Javascript
- r - 带有 Docker 的 RSelenium 在 RScript 中失败,但在 RStudio 中工作
- json - 如何将 JSON 数组解组为类数组
- python - 将 Pandas 数据框中的重复行与多列相加
- c - 在C中用空格分割每一行
- ios - 如何在 Swift 中解析 Json 响应
- rfid - RFID超高频卡片复印