Reputation: 25914
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.
Upvotes: 0
Views: 1113
Reputation: 311865
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
}
]
Upvotes: 2