Mongodb:查找城市中的邮政编码总数,还显示城市的状态

时间:2015-03-27 07:21:11

标签: mongodb zipcode

SQL等效 -

select state, city, count(distinct zip) from zipcodes group by state, city;

以下工作正常 -

    db.zipcodes.aggregate( [ 

    { $group: { _id: { state: "$state", city: "$city", zipcode: "_id"}, zip: { $sum: 1 } } },

    { $group: {  _id: "$_id.city", zcount: {$sum: "$zip"}} },

    {$sort: {zcount: -1} }
 ] )

但我无法显示城市的状态。 请帮助。

以下是文档("_id" is the zipcode)

的格式
    {
    "_id" : "01002",
    "city" : "CUSHMAN",
    "loc" : [
            -72.51565,
            42.377017
    ],
    "pop" : 36963,
    "state" : "MA"
}

1 个答案:

答案 0 :(得分:0)

db.zipcodes.aggregate( [
{ $group: { _id: { state: "$state", city: "$city", z:"_id"}, total: { $sum: 1 } } }, { $group: { _id: {state:"$_id.state", city:"$_id.city"}, count: {$sum: "$total"}} } , {$sort: {count: -1} }
] )

输出 - { "_id" : { "state" : "PA", "city" : "PHILADELPHIA" }, "count" : 48 } { "_id" : { "state" : "IL", "city" : "CHICAGO" }, "count" : 47 } { "_id" : { "state" : "TX", "city" : "SAN ANTONIO" }, "count" : 45 } { "_id" : { "state" : "TX", "city" : "DALLAS" }, "count" : 44 } { "_id" : { "state" : "MO", "city" : "KANSAS CITY" }, "count" : 41 }

这个输出看起来不错,但不确定它是否正确