我需要了解 MongoCollection->group() 功能。group() 的 PHP 手册说明如下:
<?php
$collection->insert(array("category" => "fruit", "name" => "apple"));
$collection->insert(array("category" => "fruit", "name" => "peach"));
$collection->insert(array("category" => "fruit", "name" => "banana"));
$collection->insert(array("category" => "veggie", "name" => "corn"));
$collection->insert(array("category" => "veggie", "name" => "broccoli"));
$keys = array("category" => 1);
$initial = array("items" => array());
$reduce = "function (obj, prev) { prev.items.push(obj.name); }";
$g = $collection->group($keys, $initial, $reduce);
echo json_encode($g['retval']);
?>
结果数组类似于:
[{"category":"fruit","items":["apple","peach","banana"]},{"category":"veggie","items":["corn","broccoli"]}]
现在,我看到MongoCode reduce() 函数将项目的名称推送到结果数组中。但是如果我想在名称之外再推一个字段,即水果的颜色呢?
基本上,我需要的是有这样的输出:
[{"category":"fruit","items":[["apple", "red"],["peach", "peach"],["banana", "yellow"]]},{"category":"veggie","items":[["corn", "yellow"],["broccoli", "green"]]}]
所以我认为我应该以某种不同的方式 push() ......究竟如何?我在任何地方都找不到正确的语法。
在此先感谢,并为我糟糕的英语感到抱歉:-)
弗朗切斯科