Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...