我正在尝试在我的一个 MongoDB 数据库集合上创建一个简单的映射/归约函数。 我得到了数据,但它看起来不对。我不确定 map 部分。我可以这样使用 IF/ELSE 吗?
更新
我想获得拥有这些文件的作者数量。换句话说,有多少作者拥有上传的文件,因此有多少作者没有文件。
集合中的对象如下所示:
{
"_id": {
"$id": "4fa8efe33a34a40e52800083d"
},
"file": {
"author": "john",
"type": "mobile",
"status": "ready"
}
}
map/reduce 看起来像这样:
$map = new MongoCode ("function() {
if (this.file.type != 'mobile' && this.file.status == 'ready') {
if (!this.file.author) {
return;
}
emit (this.file.author, 1);
}
}");
$reduce = new MongoCode ("function( key , values) {
var count = 0;
for (index in values) {
count += values[index];
}
return count;
}");
$this->cimongo->command (array (
"mapreduce" => "files",
"map" => $map,
"reduce" => $reduce,
"out" => "statistics.photographer_count"
)
);
最佳答案
我觉得 map 部分没问题。我会稍微改变 reduce 部分。
values.forEach(function(v) {
count += v;
}
您应该不使用for in
循环来迭代一个数组,它不是为了这样做。它用于枚举对象的属性。 Here is更详细的解释。
为什么你认为你的数据是错误的?你的源数据是什么?你得到了什么?你希望得到什么?
关于mongodb - 在 map reduce 中使用 IF/ELSE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11577123/