Reputation: 3457
I have a collection in MongoDB in this 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 is my mapReduce function
m = function() { emit(this.cust_id, 1); }
r = function (k, vals) { var sum = 0; for (var i 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 this i am geting the output as
{ "_id" : "sade", "value" : 2 }
{ "_id" : "samueal", "value" : 2 }
but i need genearte a Report output in this 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 anybody please help me how to achive , its
Edited Part
Currently I am getting the output as
{ "_id" : "dsstest 2011-03-09", "value" : 4 }
{ "_id" : "dsstest 2011-03-10", "value" : 14 }
Is it possible that i can get in this format
{ "_id" : "dsstest" , "date" : "2011-03-09", "value" : 4 }
{ "_id" : "dsstest" , "date" : "2011-03-10", "value" : 14 }
Upvotes: 0
Views: 258
Reputation: 4225
Your mapping function is insufficient as it doesn't produce key that has the date in it.
I also don't quite understand why in the sample of what you want sade
gets two logins. From what you are saying you want, you should need:
var m = function() {
var aux = this.created_at.indexOf(' ');
aux = this.created_at.substring(0,aux);
// this 'if' block will filter out the entries you don't want
// to be included in the 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;
for (i=0; i<l; i++) {
r+=values[i];
}
return r;
}
And to run:
> db.logins.mapReduce(m, r, { query : q(), out : "userLoginCountMonthly" });
And finally, to produce the report:
> db.userLoginCountMonthly.find().forEach(function(e){print(e._id.cust +' ' + e._id.day+' '+e.value);})
This would list the amount of logins for each user, for each day (within your search scope).
Upvotes: 1