【发布时间】: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