首页 > 解决方案 > 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"
    ]
}

标签: arraysdatabasemongodbmongodb-query

解决方案


您可以简单地使用$addToset而不是$last获取所有postal_codes.

$match附带说明:您可以通过将中间结果集推到state较早阶段来减少中间结果集,从而使您的代码更具性能。

db.collection.aggregate([
  {
    $match: {
      "state": "NY"
    }
  },
  {
    $group: {
      _id: "$city",
      population: {
        $sum: "$pop"
      },
      postal_codes: {
        $addToSet: "$_id"
      }
    }
  }
])

这是Mongo游乐场供您参考。


推荐阅读