[英]Can't get Map/Reduce to work with MongoDB
I've got this code: 我有以下代码:
// construct map and reduce functions
$map = new MongoCode("
function() { ".
"var key = {date: this.timestamp.getFullYear()+this.timestamp.getMonth()+this.timestamp.getDate()};".
"emit(key, {count: 1});
}"
);
$reduce = new MongoCode("
function(k, vals) { ".
"var sum = 0;".
"for (var i in vals) {".
"sum += vals[i];".
"}".
"return sum;".
"}"
);
$dates = $db->command(array(
"mapreduce" => "items",
"map" => $map,
"reduce" => $reduce,
//"query" => array("type" => "sale"),
"out" => array("merge" => "distinct_dates")
)
);
But get this error when testing: 但是在测试时出现此错误:
Array ( [assertion] => map invoke failed: JS Error: TypeError: this.timestamp.getFullYear is not a function nofile_b:0 [assertionCode] => 9014 [errmsg] => db assertion failure [ok] => 0 ) Cron run finished.
Array([assertion] =>映射调用失败:JS错误:TypeError:this.timestamp.getFullYear不是函数nofile_b:0 [assertionCode] => 9014 [errmsg] =>数据库声明失败[ok] => 0)Cron运行完成。
Each object in the collection has a timestamp, from which I want to extract a date (Ymd), and put each distinct date in a new collection. 集合中的每个对象都有一个时间戳,我想从中提取日期(Ymd),并将每个不同的日期放入新的集合中。
In MongoDB you cannot store Date objects as is. 在MongoDB中,您不能按原样存储Date对象。 I suppose, that your timestamp has int type.
我想,您的时间戳记为int类型。 I hope, if you will define your map function such way everything will be ok:
我希望,如果您以这种方式定义地图函数,那么一切都会好的:
$map = new MongoCode("
function(){
var date = new Date(this.timestamp * 1000) //JS Date need milliseconds
var key = date.getFullYear() + date.getMonth() + date.getDate();
emit(key, {count: 1})
}
")
The problem lies in that your "timestamp" field is not of the correct type. 问题在于您的“时间戳”字段的类型不正确。 If you stored it as a pure string, something like:
如果将其存储为纯字符串,则类似于:
"timestamp" : "Wed May 05 2010 15:37:58 GMT-0400 (EDT)"
You will get this error. 您将收到此错误。 Changing it to the following will cause your map to work as expected:
将其更改为以下内容将使您的地图按预期工作:
new Date("Wed May 05 2010 15:37:58 GMT-0400 (EDT)")
You'll know you're on the right track when you see it stored as an ISODate()
object in Mongo's output. 当您看到它存储为Mongo输出中的
ISODate()
对象时,您就会知道自己ISODate()
正确的轨道上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.