I have documents as the below in mongodb { "_id" : ObjectId("4f956dee76ddb26752026e8f"), "page" : "home", "visited" : ISOdate(23/02/2013) }, { "_id" : ObjectId("4f956dee76ddb26752026e8f"), "page" : "home", "visited" : ISOdate(24/02/2013) }, { "_id" : ObjectId("4f956dee76ddb26752026e8f"), "page" : "home", "visited" : ISOdate(24/02/2013) } , { "_id" : ObjectId("4f956dee76ddb26752026e8f"), "page" : "home", "visited" : ISOdate(25/02/2013) } I want to get the day along with the count in mongodb using nodejs. It should return: day: 23/02/2013, count:1 , day: 24/02/2013, count:2 ,day: 25/02/2013, count:1.the result should be sorted in day so 23rd is first 24th is second and 25th is third. There are lots of entries around 1 million .
Firstly you have duplicate ObjectIds in there so that is bad data.
Lastly you should be able to build a query using aggregates something like this: (assuming you are on mongodb 2.2 + ).
db.mytable.aggregate([ {$group : {_id:"$visited", total:{$sum:1}}}, {$sort:{visited:-1}}])
/**
* group by day
* @link https://gist.github.com/phnessu4/5636642
* @param query document {key1:123,key2:456}
*/
var count_by_day = function(query){
return db.action.group(
{
keyf: function(doc) {
var date = new Date(doc.time);
var dateKey = (date.getMonth()+1)+"/"+date.getDate()+"/"+date.getFullYear();
return {'date': dateKey};
},
cond:query,
initial: {count:0},
reduce: function(obj, prev) {
prev.count++;
}
});
}
count_by_day({this:'is',the:'query'})
try this. i'm not sure your condition detail . you need write the query by yourself.
hope this can help you.