MongoDB 3-level aggregation -
suppose have list of schools each school assigned city, state (province) , country.
is possible build aggregated list of unique cities/states/countries mongodb aggregation framework?
what have:
[ { "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", }
]
what need get:
[ { "country" : "germany", "states" : [ { "state" : "hessen", "cities" : [frankfurt,...] } ] }, { "country" : "usa", "states" : [ { "state" : "ca", "cities" : [san-francisco, los angeles, ...] } { "state" : "co", "cities" : [boulder, denver, ...] } ] },
]
keeping stages simple. , no need $addtoset
since 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 3 group stage aggregation
Comments
Post a Comment