本文介绍了在聚合函数中跳过计数 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

推荐答案

小组阶段正在根据给定的 _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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 02:47