我在MongoDB中有一个这种格式的集合
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"
}
这是我的mapReduce函数
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" });
有了这个,我将输出作为
{ "_id" : "sade", "value" : 2 }
{ "_id" : "samueal", "value" : 2 }
但我需要以这种格式生成报告输出
例如
Name Date Logins
sade 2011-03-09 1
sade 2011-03-10 2
samueal 2011-03-09 1
samueal 2011-03-10 1
有人可以帮助我如何实现,
编辑部分
目前我的输出为
{ "_id" : "dsstest 2011-03-09", "value" : 4 }
{ "_id" : "dsstest 2011-03-10", "value" : 14 }
我可以使用这种格式吗
{ "_id" : "dsstest" , "date" : "2011-03-09", "value" : 4 }
{ "_id" : "dsstest" , "date" : "2011-03-10", "value" : 14 }
答案 0 :(得分:1)
您的映射功能不足,因为它不会生成包含日期的键。
我也不太明白为什么在你想要的样本中sade
获得两次登录。根据你的意思,你需要:
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;
}
跑步:
> db.logins.mapReduce(m, r, { query : q(), out : "userLoginCountMonthly" });
最后,制作报告:
> db.userLoginCountMonthly.find().forEach(function(e){print(e._id.cust +' ' + e._id.day+' '+e.value);})
这将列出每个用户的登录量,每天(在您的搜索范围内)。