MongoDB : query collection based on Date -
i have collection in mongodb in format
db.logins.find().pretty() { "cust_id" : "samueal", "created_at" : "2011-03-09 10:31:02.765" } { "cust_id" : "sade", "created_at" : "2011-03-09 10:33:11.157" } { "cust_id" : "sade", "created_at" : "2011-03-10 10:33:35.595" } { "cust_id" : "samueal", "created_at" : "2011-03-10 10:39:06.388" }
this mapreduce function
m = function() { emit(this.cust_id, 1); } r = function (k, vals) { var sum = 0; (var in vals) { sum += vals[i]; } return sum; } q = function() { var currentdate = new date(); currentdate.setdate(currentdate.getdate()-32); var month = (currentdate.getmonth() < 10 ? "0"+ (currentdate.getmonth()+1) : (currentdate.getmonth()+1)); var date = currentdate.getfullyear() + "-" + month ; var patt = new regexp(date); var query = {"created_at":patt}; return query; } res = db.logins.mapreduce(m, r, { query : q(), out : "userlogincountmonthly" });
with geting output
{ "_id" : "sade", "value" : 2 } { "_id" : "samueal", "value" : 2 }
but need genearte report output in format
for example
name date logins sade 2011-03-09 1 sade 2011-03-10 2 samueal 2011-03-09 1 samueal 2011-03-10 1
could please me how achive ,
edited part
currently getting output
{ "_id" : "dsstest 2011-03-09", "value" : 4 } { "_id" : "dsstest 2011-03-10", "value" : 14 }
is possible can in format
{ "_id" : "dsstest" , "date" : "2011-03-09", "value" : 4 } { "_id" : "dsstest" , "date" : "2011-03-10", "value" : 14 }
your mapping function insufficient doesn't produce key has date in it. don't quite understand why in sample of want sade
gets 2 logins. saying want, should need:
var m = function() { var aux = this.created_at.indexof(' '); aux = this.created_at.substring(0,aux); // 'if' block filter out entries don't want // included in result. if (aux < "2011-11-11") { return; } emit({cust:this.cust_id,day:aux},1); } var r = function(k, values) { var l = values.length; var r = 0; var i; (i=0; i<l; i++) { r+=values[i]; } return r; }
and run:
> db.logins.mapreduce(m, r, { query : q(), out : "userlogincountmonthly" });
and finally, produce report:
> db.userlogincountmonthly.find().foreach(function(e){print(e._id.cust +' ' + e._id.day+' '+e.value);})
this list amount of logins each user, each day (within search scope).
Comments
Post a Comment