使用多个分组字段的Mongodb计算不同值的数量

7
我有一个交易表,记录了员工所休的假期。 我需要在mongodb中实现以下sql场景。
select employee,month,year,count(distinct (holiday_type) from 
transactions group by employee,month,year

我需要在Mongodb中使用聚合功能,创建的Mongo查询语句如下,但是它给出了错误的结果。

db.transactions.aggregate([
    { "$group": { 
        "_id": { 
            "Month": { "$month" : "$date" }, 
            "Year": { "$year" : "$date" },
            "employee" : "$employee",
            "holiday_type" : "$holiday_type"
        },
        "Count_of_Transactions" : { "$sum" : 1 }
     }}
 ]);

我在使用mongodb中的count distinct逻辑时感到困惑。有什么建议吗?

1个回答

11

已经有了一部分,但你需要首先获得“holiday_type”的“distinct”值,然后再次使用$group

db.transactions.aggregate([
    { "$group": { 
        "_id": { 
            "employee" : "$employee",
            "Month": { "$month" : "$date" }, 
            "Year": { "$year" : "$date" },
            "holiday_type" : "$holiday_type"
        },
     }},
     { "$group": {
         "_id": {
            "employee" : "$_id.employee",
            "Month": "$_id.Month",
            "Year": "$_id.Year"
         },
         "count": { "$sum": 1 }
     }}
 ], { "allowDiskUse": true }
 );

在SQL中,“distinct”通常被视为一种分组操作。因此,它需要进行双重$group操作才能得到正确的结果。


在执行此查询时,我遇到了以下错误:assert: command failed: { "errmsg" : "exception: Exceeded memory limit for $group, but didn't allo w external sort. Pass allowDiskUse:true to opt in.", "code" : 16945, "ok" : 0 } : aggregate failed - Karthi
@Karthi 在MongoDB 2.6中,$group操作的内存使用限制已经降低,但是你的集合可能特别大。您可以在方法参数的“options”部分中添加“allowDiskUse”来对抗这个问题,就像我在编辑中所包含的那样。另请参阅aggregate命令手册页面。 - Neil Lunn
你是对的。我在查询中没有包含allowDiskuse。这非常有帮助。 - Karthi
如果我想要做一个求和函数,例如说小时数,哪个分组段应该有求和函数,比如(总计:$sum:$hours),这需要跨月份、年份和员工进行分组。 - Karthi
@Karthi,那听起来像是另一个问题,最好用问题的形式表达,而不是简短的评论。请随意提问。 - Neil Lunn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接