0

I have a bunch of documents:

{"timestamp" : 1304535236, "value" : 2}
{"timestamp" : 1304532236, "value" : 5}
{"timestamp" : 1304535647, "value" : 1}

where timestamp is a unix timestamp. I would like to sum up the total number of value for each day. Note: There may be a number of documents whose timestamps fall on the same day just at different times.

If I do a normal mongo group query is sums up per timestamp because they are all unique, which is un-helpful.

1 Answer 1

2

You have to convert your timestamp values into Date objects so that you can group by day.

Using Rachel's answer as a starting point (in the shell):

db.test.group({
  keyf: function(doc) {
    var date = new Date(doc.timestamp*1000);
    var dateKey = (date.getMonth()+1) + "/" + 
                  date.getDate() + "/" + 
                  date.getFullYear();
    return {day: dateKey};
  },
  initial: {value: 0},
  reduce: function(curr, result) { result.value += curr.value; }
});

returns:

[
  {
    "day": "5/4/2011",
    "value": 8
  }
]
1
  • answer for shell and question for Python
    – Thijs
    Nov 20, 2014 at 17:58

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.