聚合函数中跳过计数0 [英] skipped count 0 in aggregate function

查看:31
本文介绍了聚合函数中跳过计数0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持了几天.我正在尝试获取count: 0,其中在给定的时间段内没有文档.这是我目前正在使用的聚合函数:

I'm stuck on this for couple of days. I'm trying to get the count: 0 where there is no documents in the given time period. This is the aggregate function I'm using at the moment:

var getCount = function(timeBlock, start, end, cb) {

    Document.aggregate(
    {
        $match: {
            time: {
                $gte: new Date(start),
                $lt: new Date(end)
            }
        }
    },

    {
        $project: {
            time: 1,
            delta: { $subtract: [
                new Date(end),
                '$time'
            ]}
        }
    },

    {
        $project: {
            time: 1,
            delta: { $subtract: [
                "$delta",
                { $mod: [
                    "$delta",
                    timeBlock
                ]}
            ]}
        }
    },

    {
        $group: {
            _id: { $subtract: [
                end,
                "$delta"
            ]},
            count: { $sum: 1 }
        }
    },

    {
        $project: {
            time: "$_id",
            count: 1,
            _id: 0
        }
    },

    {
        $sort: {
            time: 1
        }

    }, function(err, results) {
        if (err) {
            cb(err)
        } else {
            cb(null, results)
        }
    })
}

我尝试使用$cond,但是没有运气

I tried using $cond, but with no luck

推荐答案

group阶段基于给定的_id进行分组,并计算最终进入该组的前一阶段的文档数,从而生成文档.因此,零计数是从属于该组的0个输入文档创建文档的结果.以这种方式考虑,很显然聚合管道不可能为您做到这一点.它不知道所有丢失"的时间段是什么,并且无法凭空发明适当的文档.如果您需要在空白时间段内将计数明确地设为0,那么重新运用有关缺失时间段的额外知识来完成图片,这似乎是一个合理的解决方案(不是"hacky").

The group stage is producing documents based on grouping on your given _id and counting the number of documents from the previous stage that end up in the group. Hence, a count of zero would be the result of a document being created from 0 input documents belonging to the group. Thinking about it this way, it's clear that there's no way the aggregation pipeline can do this for you. It doesn't know what all of the "missing" time periods are and it can't invent the appropriate documents out of thin air. Reapplying your extra knowledge about the missing time periods to complete the picture at the end seems like a reasonable solution (not "hacky") if you need to have an explicit count of 0 for empty time periods.

这篇关于聚合函数中跳过计数0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆