kusanagi
kusanagi

Reputation: 14614

MongoCollection group question

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

?>

not clear line $keys = array("category" => 1); why need write "category" => 1 instead of symply write "category" ?

Upvotes: 0

Views: 204

Answers (1)

Gates VP
Gates VP

Reputation: 45287

why need write "category" => 1 instead of symply write "category" ?

The query engine for MongoDB used JSON objects. So everything is a key-value pair. The PHP driver is representing key-value pairs using hash tables (or dictionaries).

If you look at the aggregation documentation, it has the following example:

key: { a:true, b:true }

In PHP this would be represented as

$key: array('a' => 1, 'b' => 1)

I agree that the 1 seems unnecessary, but it's there to keep the JSON syntax valid.

Upvotes: 1

Related Questions