Вопрос

I need to understand a MongoCollection->group() feature. PHP manual for group() states what follows:

<?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']);

?>

with a result array similar to:

[{"category":"fruit","items":["apple","peach","banana"]},{"category":"veggie","items":["corn","broccoli"]}]

now, I see that the MongoCode reduce() function pushes the item's name into the result array. But what if I want to push one more field besides the name, i.e. the fruit's color?

basically, what I need is to have an output like this:

[{"category":"fruit","items":[["apple", "red"],["peach", "peach"],["banana", "yellow"]]},{"category":"veggie","items":[["corn", "yellow"],["broccoli", "green"]]}]

so I think I should push() somehow differently... how exactly? I can't find the right syntax anywhere.

thanks in advance and sorry for my poor english :-)

Francesco

Это было полезно?

Решение

I nailed it! it's much more straightforward than I thought. it's all plain JavaScript!

all you have to do is to build your own array (even an associative one) and then push it into the main array that you named while invoking the reduce() function.

here's an example:

$reduce = "function (obj, prev) { prev.items.push([obj.name, obj.color]); }";

actually worked, but I wanted more: an associative array. so I did this:

reduce = 'function (obj, prev) {
        var tempArr = {
            "name" : obj.name,
            "color" : obj.color,
        };
        prev.pages.push(tempArr);
    }';

and everybody lived happily ever after.

Другие советы

Right now, the key "name" is a string holding names of fruits. Try to store an array into "name" something like below:

$collection->insert(array("category" => "fruit", "name" => array("apple", "red")));

I do not know anything about MongoDB but just thought about the logic. This might help you.

@rajesh I have further investigated the problem. perhaps it's just a matter of correct use of MongoCode's inner Javascript.

that is, probably using the push() function like this

$reduce = "function (obj, prev) { prev.items.push([obj.name, obj.color]); }";

could do the trick. I'll test it tomorrow and hopefully file the proper answer.

EDIT answer was posted

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top