sicr
sicr

Reputation: 2218

Aggregation query in MongoDB

I'm looking to write a pretty straightforward aggregation query in MongoDB, but struggling with a certain part.

What I would like to do is pull the sum of all records within the last 7 days grouped by day. It's easy enough to define the date 7 days ago as UTC, but I'd like to do it programmatically so I don't need to work out the UTC date everytime. For instance instead of 1341964800 i'd like to specify something like date() - 7 days.

Here's the current aggregation function I have which works:

db.visits_calc.group(
    { key:{date:true}, 
    cond:{date:{$gt:1341964800}}, 
    reduce:function(obj,prev) {prev.csum += obj.total_imp}, 
    initial:{csum:0}
});

Thanks in advance!

Upvotes: 0

Views: 481

Answers (1)

narced133
narced133

Reputation: 752

You can perform arithmetic on the milliseconds timestamp returned by Date.now() to find the appropriate timestamp for 7 days ago. You need to subtract the number of milliseconds in 7 days (1000ms/s, 60 s/min, 60min/hr, 24 hrs/dy, 7dys/wk).

var weekAgo = Date.now() - (1000*60*60*24*7);
db.visits_calc.group(
    { key:{date:true}, 
    cond:{date:{$gt:weekAgo}}, 
    reduce:function(obj,prev) {prev.csum += obj.total_imp}, 
    initial:{csum:0}
});

Upvotes: 3

Related Questions