Proper way to get a PHP array() from aggregate() or convert a MongoDB\Driver\Cursor to array()

Some documents on the DB have the field ‘Assunto’, I wanted to count how many times different values for ‘Assunto’ occur (ignoring when the field does not exist, so I did this query:

$result = $collection->aggregate([
[ '$match' => ['Assunto' => ['$nin' => [null]]] ],
[ '$sortByCount'=> '$Assunto' ],
[ '$sort' => ['Count' => -1] ]
]);

The query works properly, my issue is with the return from aggregate. From the documentation it returns either “A MongoDB\Driver\Cursor or ArrayIterator object”.

Also from the documentation typeMap : “Optional. The type map to apply to cursors, which determines how BSON documents are converted to PHP values. Defaults to the collection’s type map”.

I read solutions on Stack Overflow on altering the collection’s typeMap to convert the cursor to an array but I couldn’t get them to work for my case, from my understanding I have multiple MongoDB\Driver\Cursor and it was returning only the first one of them.

The next solution from Stack Overflow was to encode the cursor to JSON then decode it to an array. Like this:

//Convert $result, a MongoDB\Driver\Cursor to array()
$objects = json_decode(json_encode($result->toArray(),true));

The problem is that this produces an stdClass Object just like this:

So, to convert this stdClass to an array I need to do the same code yet again: (sorry for blurry image, happens after resizing)

//Convert stdClass to Array
$array=json_decode(json_encode($objects),true);

This produces the expected output. But doing all this process seems like a waste. What would be the proper way to convert the returned values from aggregate into and array in my case? The entire code snippet in case it helps:

$result = $collection->aggregate([
[ '$match' => ['Assunto' => ['$nin' => [null]]] ],
[ '$sortByCount'=> '$Assunto' ],
[ '$sort' => ['Count' => -1] ]
]);

//Convert $result, multiple MongoDB\Driver\Cursor objects into stdClass Objects
$objects = json_decode(json_encode($result->toArray(),true));

//Convert stdClass Objects into Array()
$array=json_decode(json_encode($objects),true);

return $array;

That was my mistake. I should add true as the second parameter in the json_decode funcion like this:

$array = json_decode(json_encode($result->toArray(),true), true);

This converts the BSON documents to an array instead of an std object in a single line.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.