如何使用聚合管道按两级分组进行排序?

时间:2015-08-26 00:23:55

标签: mongodb aggregation-framework

鉴于此数据:

[ {country:"US", city:"NY", cnt: 10}
  {country:"IT", city:"MI", cnt:  9}
  {country:"US", city:"LA", cnt:  8}
  {country:"IT", city:"RM", cnt: 20} ]

有没有办法使用mongoDB聚合管道来创建一个看起来像这样的结果数组(不是基于alpha代码,只是cnt):

[ {country:"IT", city:"RM", cnt:20}
  {country:"IT", city:"MI", cnt: 9}
  {country:"US", city:"NY", cnt:10}
  {country:"US", city:"LA", cnt: 8} ]

}

换句话说,一个数组按总数最高的国家/地区排序(降序),然后是每个城市的最高总数?

我可以按国家/地区或国家/地区分组,但不会给我上述结果。一个给我两行,每个国家的总数,另一个给我四行国家城市总数,但没有按总数最高的国家排序。

1 个答案:

答案 0 :(得分:1)

只需在$group之后添加$sort

{ "$sort": { "country": 1, "cnt": -1  } }

结果:

{ "country" : "IT", "city" : "RM", "cnt" : 20 }
{ "country" : "IT", "city" : "MI", "cnt" : 9 }
{ "country" : "US", "city" : "NY", "cnt" : 10 }
{ "country" : "US", "city" : "LA", "cnt" : 8 }

要使用总计,然后分组以获得总计数:

{ "$group": {
  "_id": "$country",
  "cities": { "$push": {
    "city": "$city",
    "cnt": "$cnt"
  }},
  "totalCount": { "$sum": "$cnt" }
}},
{ "$unwind": "$cities" },
{ "$sort": { "totalCount": -1, "_id": 1, "cities.cnt": -1 }},
{ "$project": {
  "_id": 0,
  "country": "$_id",
  "city": "$cities.city",
  "cnt": "$cities.cnt"
}}

投射出来以获得相同的结果