Если поле «метка» является датой напечатанного значения, то вы можете использовать оператор $month
проекции из aggregation framework, чтобы захватить месяц из вашей временной метки, затем 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);
});