MongoDB 聚合或获取集合中记录文档的平均每日平均计数

MongoDB aggregate or get the Mean daily average count of recorded documents in a collection

每次将文档添加到 MongoDB 集合时,我都会保存当前时间 Date.now()。假设这 3 个文档具有以下格式:

# Doc 1
    {
      date: ISODate("2017-01-25T09:47:40.000Z"),
      reports: 5
    }
# Doc 2
    {
      date: ISODate("2017-01-24T09:47:40.000Z"),
      reports: 5
    }
# Doc 3
    {
      date: ISODate("2017-01-23T09:47:40.000Z"),
      reports: 5
    }

基本上,数学公式是(total reports) divided by the (count of days from the oldest date until date today)

使用 mongo shell 进行聚合的 easiest/fastest 方法是什么?

谢谢!

您可以尝试以下聚合。

$match保持记录$lte比今天,$group通过null并计算$sum来统计报告,$min (最早的)日期和 $project 通过除以总报告和天数来计算平均值。

db.collection.aggregate({
    $match: {
        date: {
            $lt: new ISODate()
        }
    }
}, {
    $group: {
        _id: null,
        oldestDate: {
            $min: "$date"
        },
        sumReports: {
            $sum: "$reports"
        }
    }
}, {
    $project: {
        _id: 0,
        avgReports: {
            $divide: ["$sumReports", {
                $divide: [{
                    $subtract: [new ISODate(), "$oldestDate"]
                }, 1000 * 60 * 60 * 24]
            }]
        }
    }
})