MongoDB - 按日期聚合,右对齐边界

时间:2013-06-07 22:35:28

标签: mongodb aggregation-framework

我在MongoDB中有一些数据包含10分钟的期间最新总和:

db.test.insert({perEnd: ISODate('2013-06-05T18:00:00'), val: 7.3})
db.test.insert({perEnd: ISODate('2013-06-05T18:10:00'), val: 6.23})
db.test.insert({perEnd: ISODate('2013-06-05T18:20:00'), val: 4.1})
db.test.insert({perEnd: ISODate('2013-06-05T18:30:00'), val: 0.21})
db.test.insert({perEnd: ISODate('2013-06-05T18:40:00'), val: 12.1})
db.test.insert({perEnd: ISODate('2013-06-05T18:50:00'), val: 6.0})
db.test.insert({perEnd: ISODate('2013-06-05T19:00:00'), val: 8.9})
db.test.insert({perEnd: ISODate('2013-06-05T19:10:00'), val: .98})
db.test.insert({perEnd: ISODate('2013-06-05T19:20:00'), val: 14.7})

我想汇总以查找每个小时结束时段的总和,因此我应该得到以下值:

ending 2013-06-05 18:00:00 - 7.3
ending 2013-06-05 19:00:00 - 37.54
ending 2013-06-05 20:00:00 - 15.68

使用内置日期运算符不起作用,因为它们将所有日期向下舍入(截断)到最近的边界,我需要围绕向上

> db.test.aggregate({$group: {_id: {Year: {$year: "$perEnd"},
                                    Day: {$dayOfYear: "$perEnd"},
                                    Hour: {$hour: "$perEnd"}},
                              sum: {$sum: "$val"}}})
{
        "result" : [
                { "_id" : { "Year" : 2013,
                            "Day" : 156,
                            "Hour" : 19 },
                  "sum" : 24.58 },

                { "_id" : { "Year" : 2013,
                            "Day" : 156,
                            "Hour" : 18 },
                  "sum" : 35.940000000000005 }
        ],
        "ok" : 1
}

任何人都能找到一种方法来实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

您可以使用mongodb map-reduce执行此操作:

var map = function(){
    var date = new Date(this.perEnd.getTime());
    if(date.getMinutes() > 0){
        date.setHours(date.getHours() + 1, 0, 0, 0);
    } else {
        date.setHours(date.getHours(), 0, 0, 0);
    }
    emit(date, this.val);
};

var reduce = function(key, values){
    return Array.sum(values)
};

db.collection.mapReduce(map, reduce, {out : {inline : 1}}, callback);

对于您的数据,我得到以下结果:

[ { _id: Wed Jun 05 2013 21:00:00 GMT+0300 (EEST), value: 7.3 },
  { _id: Wed Jun 05 2013 22:00:00 GMT+0300 (EEST), value: 37.54 },
  { _id: Wed Jun 05 2013 23:00:00 GMT+0300 (EEST), value: 15.68 } ]