Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

javascript - skipped count 0 in aggregate function

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)
        }
    })
}

I tried using $cond, but with no luck

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...