0

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!

1 Answer 1

3

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}
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.