Map-Reduce the number of documents per minute MongoDB

I have a MongoDB collection that stores created_atin every document. They are saved as a MongoDB date object, for example.

{ "_id" : "4cacda7eed607e095201df00", "created_at" : "Wed Oct 06 2010 21:22:23 GMT+0100 (BST)", text: "something" }
{ "_id" : "4cacdf31ed607e0952031b70", "created_at" : "Wed Oct 06 2010 21:23:42 GMT+0100     (BST)", text: "something" }
....

I would like to count the number of items created between every minute, so I can pass the data to Google Charts to create something like this:

alt text

How can I do this using the map reduction function, or is there some kind of moral MongoDB function that I could use instead?

+5
source share
2 answers

The map function should emit a timestamp object, adjust to a minute and count 1. The reduction function should summarize all values:

map = function() {
    var created_at_minute = new Date(this.created_at.getFullYear(),
                                     this.created_at.getMonth(), 
                                     this.created_at.getDate(), 
                                     this.created_at.getHours(), 
                                     this.created_at.getMinutes());
    emit(created_at_minute, {count: 1});
}

reduce = function(key, values) { 
    var total = 0;
    for(var i = 0; i < values.length; i++) { 
        total += values[i].count; 
    }
    return {count: total};
}
+8

group.


db.stat.group({key:{"create_at_minute":true}
              ,initial:{count:0}
              ,reduce:function(doc,out){out.count++}})

create_at_minute - create_at, .

0

All Articles