猫鼬:按月分组时间戳

时间:2013-09-15 16:01:16

标签: node.js mongodb mongoose

我如何按月进行分组并使用只有字段时间戳的mongoose进行数量的平均值?

{ "timestamp": 1234567890, "qty": 3 }, { "timestamp": 09876543322, "qty": 5 }

我想知道每个月的平均数量。

1 个答案:

答案 0 :(得分:5)

如果'timestamp'字段是Date-typed值,那么您可以使用 来自aggregation framework$month投影操作员抓取 从您的时间戳开始的月份,然后是group

collection.aggregate([
    // Grab the month of the timestamp
    {$project: {"qty":1, "month":{$month: "$timestamp"}}},
    // Find average for each month
    {$group: {"_id":"$month", "avg_qty":{$avg:"$qty"}}}
])

如果时间戳只是一个数字,您可以使用map-reduce。某物 类似于:

var o = {};
// Get the month and qty for each document, grouping into months
o.map = function() { emit( (new Date(this.timestamp)).getMonth(), this.qty); };
// Get the average qty for each month
o.reduce = function(month, quants) { return Array.sum(quants)/quants.length; };

collection.mapReduce(o, function(err, results) {
    console.log(results);
});
相关问题