MongoDB 3级聚合 [英] MongoDB 3-level aggregation

查看:59
本文介绍了MongoDB 3级聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个学校列表,以便为每所学校分配城市,州(省)和国家/地区.

Suppose we have a list of schools so that each school is assigned city, state (province) and country.

是否可以使用MongoDB聚合框架构建唯一城市/州/国家的聚合列表?

Is it possible to build an aggregated list of unique cities/states/countries with MongoDB aggregation framework?

我所拥有的:

[
{
    "School_name" : "School #1",
    "state" : "CA"
    "city" : "San-Francisco",
    "country" : "USA",
},
{
    "School_name" : "School #2",
    "state" : "CA"
    "city" : "San-Francisco",
    "country" : "USA",
},
{
    "School_name" : "School #3",
    "state" : "CA"
    "city" : "Los Angeles",
    "country" : "USA",
},
{
    "School_name" : "School #4",
    "state" : "CO"
    "city" : "Denver",
    "country" : "USA",
},
{
    "School_name" : "School #5",
    "state" : "CO"
    "city" : "Boulder",
    "country" : "USA",
},
{
    "School_name" : "School #6",
    "state" : "Hessen"
    "city" : "Frankfurt",
    "country" : "Germany",
}

]

我需要得到什么:

[
{
 "country" : "Germany",
     "states" :  
  [     
      {
    "state" : "Hessen",
        "cities" : [Frankfurt,...]
      }
      ]
},
{
 "country" : "USA",
     "states" :  
      [
    {
    "state" : "CA",
        "cities" : [San-Francisco, Los Angeles, ...]
    }
    {
    "state" : "CO",
        "cities" : [Boulder, Denver, ...]
    }
      ]
},

]

推荐答案

使阶段保持简单.无需$addToSet,因为顶级组可以对重复项进行分类:

Keeping the stages simple. And no need to $addToSet since the top level group sorts out duplicates:

db.school.aggregate([{
    $group: { 
        _id: { 
            country: "$country",
            state: "$state", 
            city: "$city" 
        }
    }},
   {$group: { 
       _id: { 
       country: "$_id.country",
       state: "$_id.state" },
       cities: {$push: "$_id.city"} }
   },
   {$group: { 
       _id: "$_id.country",
       states: {$push: { state: "$_id.state", cities: "$cities" }} 
   }},
   {$project: { _id: 0, country: "$_id", states: "$states" }}
])

所以实际上这是三组阶段的聚合

So it is actually a three group stage aggregation

这篇关于MongoDB 3级聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆