我正在尝试在PHP中创建一个Map-Reduce命令,其中完全的功能与纯JavaScript相同,但结果却不尽相同。我在PHP中有 null 值: - (
我有“employees”集合,每位员工都有一个他/她所属的“部门”列表。
所以 Javascript map-reduce代码(有效)可以按部门获得员工人数:
map = function() {
if (!this.department) {
return;
}
for (i in this.department) {
emit(this.department[i], 1);
};
};
reduce = function(key, values) {
var total = 0;
for (i in values) {
total += values[i];
};
return total;
};
retorno = db.runCommand({
"mapreduce": "employees",
"map": map,
"reduce": reduce,
"out": "employees_by_department"
});
if (retorno.ok != 1) {
print(retorno.errmsg);
};
resultado = db.employees_by_department.find();
while ( resultado.hasNext() ) {
printjson( resultado.next() );
}
等效的 PHP代码(带有 null 值)将是:
<?php
try {
$connection = new MongoClient( "mongodb://localhost" );
$db = $connection->selectDB("employees");
} catch (Exception $e) {
printf("Error: %s: %s\n", "Error al conectarse a MongoDB: ", $e->getMessage());
die();
}
$map = new MongoCode("function() {
if (!this.department) {
return;
}
for (i in this.department) {
emit(this.department[i], 1);
};
};");
$reduce = new MongoCode("reduce = function(key, values) {
var total = 0;
for (i in values) {
total += values[i];
};
return total;
};");
$retorno = $db->command(array(
"mapreduce" => "employees",
"map" => $map,
"reduce" => $reduce,
"out" => "employees_by_department_php"
));
if ($retorno["ok"] =! 1) {
print($retorno["errmsg"]);
}
else {
$resultado = $db->selectCollection("employees_by_department_php")->find();
foreach($resultado as $dep) {
printf("_id: \"%s\", value: %d\n", $dep["_id"], $dep["value"]);
}
}
?>
有什么想法吗?
答案 0 :(得分:0)
UUpppss !!解决了!问题是拼写错误(复制粘贴问题): - |
在PHP中,reduce函数的第一行是
$reduce = new MongoCode("reduce = function(key, values) {
应该是
$reduce = new MongoCode("function(key, values) {