【问题标题】:Mongodb : Find the cities with the highest number of zipcodes and order states by highest zipcode city populationMongodb:查找邮政编码数量最多的城市,并按邮政编码城市人口最多的州排序
【发布时间】:2016-12-12 06:35:53
【问题描述】:

集合中的文档

{ "_id" : "01001", 
"city" : "AGAWAM", 
" loc" : [ -72.622739, 42.070206 ],
"pop" : 15338,
"state" : "MA" }

第一部分是在每个州寻找排名最高的城市。邮政编码(_id's)

我有这个:-

db.zips.aggregate([{ 

 $group:
  {
    _id: {state:"$state",city: "$city" }  ,
    count: {$sum:1},
    population:{$sum:"$pop"}
  }
 },
 {
 $sort:{count:-1}
}   
])

我得到的输出:-

{ "_id" : { "state" : "TX", "city" : "HOUSTON" }, "count" : 93,   "population" : 2095918 }
{ "_id" : { "state" : "CA", "city" : "LOS ANGELES" }, "count" : 56, "population" : 2102295 }
{ "_id" : { "state" : "PA", "city" : "PHILADELPHIA" }, "count" : 48, "population" : 1610956 }
{ "_id" : { "state" : "IL", "city" : "CHICAGO" }, "count" : 47, "population" : 2452177 }
{ "_id" : { "state" : "TX", "city" : "SAN ANTONIO" }, "count" : 45, "population" : 811792 }
{ "_id" : { "state" : "TX", "city" : "DALLAS" }, "count" : 44, "population" : 940191 }
{ "_id" : { "state" : "MO", "city" : "KANSAS CITY" }, "count" : 41,    "population" : 360182 }

问题是我需要找到编号最高的城市。每个州的邮政编码,所以每个州应该只出现一次,而不是一个排序列表。基本上我正在寻找每个州的邮政编码的最高值。

关于如何实现这一目标的任何想法?

【问题讨论】:

    标签: mongodb mongodb-query database nosql


    【解决方案1】:

    只需在聚合管道中添加第二个 $group 阶段,如下所示:

    db.zips.aggregate([
       {
          $group:{
             _id:{
                state:"$state",
                city:"$city"
             },
             count:{
                $sum:1
             },
             population:{
                $sum:"$pop"
             }
          }
       },
       {
          $sort:{
             count:-1
          }
       },
       {
          $group:{
             _id:"$_id.state",
             count:{
                $first:"$count"
             },
             city:{
                $first:"$_id.city"
             },
             population:{
                $first:"$population"
             }
          }
       }
    ])
    

    在线试用:mongoplayground.net/p/_Kpf37svCER

    【讨论】:

    • 谢谢!这真的帮助我清除了很多穗状花序。已经尝试了几个小时!
    猜你喜欢
    • 2010-09-30
    • 1970-01-01
    • 2013-04-05
    • 2014-01-27
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    相关资源
    最近更新 更多