Mongodb Aggregation Framework and timestamp

十年热恋 提交于 2019-12-25 11:35:06

问题


I have a collection

{ "_id" : 1325376000, "value" : 13393}
{ "_id" : 1325462400, "value" : 13393}

ObjectIds are Unix Timestamp and are storing as Number manually.(at insert time).

now I'm searching for a solution that i could calculate sum of values for each month with Aggregation Framework.


回答1:


Here is a way you can do it by generating the aggregation pipeline programmatically:

numberOfMonths=24;   /* number of months you want to go back from today's */
now=new Date();
year=now.getFullYear();
mo=now.getMonth();
months=[];
for (i=0;i<numberOfMonths;i++) {
      m1=mo-i+1; m2=m1-1;
      d = new Date(year,m1,1); 
      d2=new Date(year,m2,1);
      from= d2.getTime()/1000; 
      to= d.getTime()/1000;
      dt={from:from, to:to, month:d2};  months.push(dt); 
}
prev="$nothing";
cond={};
months.forEach(function(m) { 
      cond={$cond: [{$and :[ {$gte:["$_id",m.from]}, {$lt:["$_id",m.to]}  ]}, m.month, prev]}; 
      prev=cond; 
} );

/* now you can use "cond" variable in your pipeline to generate month */
db.collection.aggregate( { $project: { month: cond , value:1 } }, 
                         { $group: {_id:"$month", sum:{$sum:"$value"} } }
)


来源:https://stackoverflow.com/questions/17299190/mongodb-aggregation-framework-and-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!