Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a MongoCursor from ->find() to an array

Tags:

php

mongodb

$jokes = $collection->find();

How do I convert $jokes into an array?

like image 721
jini Avatar asked Oct 06 '11 03:10

jini


5 Answers

You can use PHP's iterator_to_array function, as suggested in example 1 of the MongoCursor docs:

$jokes = $collection->find();
$jokesArray = iterator_to_array($jokes);
like image 52
Chris Henry Avatar answered Oct 21 '22 08:10

Chris Henry


As a side note to Chris's answer:

array iterator_to_array ( Traversable $iterator [, bool $use_keys = true ] )

Pay attention to the optional second parameter, if it's set to true (default), the final array will be indexed using the "_id" field from each document.

If you applied a sort in the mongo query, the final array might not be what you expected, meaning that the sort order will not be preserved (unless you set the $use_keys parameter to false)

like image 39
Mihai Cicu Avatar answered Oct 21 '22 08:10

Mihai Cicu


iterator_to_array is not working for nesting more than 2 levels,

Using typeMap you can convert root and its document to array, It will work for any level of nesting

findOne($filter,$options)

$options = ["typeMap" => ['root' => 'array', 'document' => 'array']];
$collection->findOne(['myId' => $id ], $options); // returns array

find($filter,$options)

$options = ["typeMap" => ['root' => 'array', 'document' => 'array']];
$collection->find(['myId' => $id ], $options)->toArray(); 
like image 35
satya prakash patel Avatar answered Oct 21 '22 07:10

satya prakash patel


iterator_to_array() forces the driver to load all of the results into memory, so do not do this for result sets that are larger than memory! use this

$jokes = $collection->find();
foreach ($jokes as $joke) {
    var_dump($joke);
}
like image 3
Mahesh Giri Avatar answered Oct 21 '22 07:10

Mahesh Giri


a lot easier:

findeOne()->getArrayCopy();

as mentioned before: beware from loading large resultsets and convert them to an array

you can also set your preferences with the typeMap option

'typeMap' =>[
      'document' => 'array',
       'root' => 'array'
                ]
like image 2
Delcon Avatar answered Oct 21 '22 07:10

Delcon