首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mongo db查询聚合

mongo db查询聚合
EN

Stack Overflow用户
提问于 2022-09-19 16:38:59
回答 1查看 34关注 0票数 0

这是我的数据:在mongodb中

代码语言:javascript
复制
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
                        }
            },
        ]
    }

])

我希望这是查询结果中的ans

代码语言:javascript
复制
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

这个也是

代码语言:javascript
复制
   Country : "India",  total: 500  total sum
   Country : "shri lanka",  total: 2541 total sum
EN

回答 1

Stack Overflow用户

发布于 2022-09-19 17:44:06

对于第一批人

代码语言:javascript
复制
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"}}}
])

为2个人

代码语言:javascript
复制
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"}}}
])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73776671

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档