Reputation: 1753
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
Upvotes: 0
Views: 39
Reputation: 1753
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"}}}
])
Upvotes: 0