首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用MongoDB的聚合框架按性别进行年龄分布

使用MongoDB的聚合框架按性别进行年龄分布
EN

Stack Overflow用户
提问于 2018-01-09 21:39:08
回答 1查看 783关注 0票数 1

我在一个名为customers的MongoDB集合中有数千个文档,它们都具有相同的模式:

代码语言:javascript
复制
{ 
  "gender" : "male", 
  "age" : NumberInt(34)
}
{ 
  "gender" : "female", 
  "age" : NumberInt(56)
}
{ 
  "gender" : "male", 
  "age" : NumberInt(48)
}
... and so on

我想分析所有这些文档,并生成一个基本的人口统计报告,如下所示:

我可以使用$bucket将客户按年龄分组,但我不知道如何将性别整合到我的渠道中。有没有办法使用聚合框架在MongoDB中获得我需要的数据?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-09 22:03:39

$bucket中,您需要编写一个$cond定义来获取男性、女性和总计数

代码语言:javascript
复制
db.g.aggregate([
{
    $bucket:
    {
        groupBy : "$age", 
        boundaries:[0,20,30,40,50], 
        default:"other", 
        output : 
            {
                "total" : {$sum : 1}, 
                "male" : {$sum : {$cond: { if: { $eq: [ "$gender", "male" ] }, then: 1, else: 0 }}},
                "female" : {$sum : {$cond: { if: { $eq: [ "$gender", "female" ] }, then: 1, else: 0 }}}  }
            }
    }
])

输出

代码语言:javascript
复制
{ "_id" : 30, "total" : 1, "male" : 1, "female" : 0 }
{ "_id" : 40, "total" : 1, "male" : 1, "female" : 0 }
{ "_id" : "other", "total" : 1, "male" : 0, "female" : 1 }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48169456

复制
相关文章

相似问题

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