本文介绍了Mongodb聚合框架和时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个收藏集
{ "_id" : 1325376000, "value" : 13393}
{ "_id" : 1325462400, "value" : 13393}
ObjectIds是Unix Timestamp,并手动存储为Number (插入时)。
ObjectIds are Unix Timestamp and are storing as Number manually.(at insert time).
现在我正在寻找一种可以使用Aggregation Framework计算每个月的值总和的解决方案。
now I'm searching for a solution that i could calculate sum of values for each month with Aggregation Framework.
推荐答案
以下是通过编程方式生成聚合管道的一种方法:
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"} } }
)
这篇关于Mongodb聚合框架和时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!