简体   繁体   中英

mongo db query aggregate

Here is my data: in mongodb

db.population.insertMany([
    {
        "country" :"India",
        "state" : [
            {"Punjab" : { 
                            "male" : 50 ,
                            "female" : 50
                        }
            }, 
            {"Haryana" : { 
                            "male" : 150 ,
                            "female" : 140
                        }
            }, 
            {"UP" : { 
                            "male" : 120 ,
                            "female" : 160
                        }
            },
        ]
    }, {
        "country" :"Shri lanka",
        "state" : [
            {"Eastern" : { 
                            "male" : 30 ,
                            "female" : 40
                        }
            }, 
            {"North Central" : { 
                            "male" : 250 ,
                            "female" : 240
                        }
            }, 
            {"Uva" : { 
                            "male" : 120 ,
                            "female" : 260
                        }
            },
        ]
    }

])

I want this ans from query result

Country : "shri lanka", "state" : "Eastern", total: 70
Country : "North Central", "state" : "Eastern", total: 490
Country : "Uva", "state" : "Eastern", total: 380
Country : "Haryana", "state" : "Punjab", total: 190
Country : "India", "state" : "Punjab", total: 100

And this one also

   Country : "India",  total: 500  total sum
   Country : "shri lanka",  total: 2541 total sum

For first ans

db.population.aggregate([
  {$unwind:"$state"},
  {$project:{"country":1,"state":{$objectToArray: "$state"}}},
  {$unwind:"$state"}, 
  {$project:{"country":"$country","state":"$state.k",
  "total":{$sum:["$state.v.male","$state.v.female"]}}},
  { $group: { _id: "$country" , "total" : {$sum: "$total"}}}
])

for 2 ans

db.population.aggregate([
  {$unwind:"$state"},
  {$project:{"country":1,"state":{$objectToArray: "$state"}}},
  {$unwind:"$state"}, 
  {$project:{"country":"$country","state":"$state.k",
  "total":{$sum:["$state.v.male","$state.v.female"]}}},
  { $group: { _id: "$country" , "total" : {$sum: "$total"}}}
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM