开发者

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

$jokes = $collection->find();

How do I convert 开发者_StackOverflow$jokes into an array?


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);


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(); 


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)


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);
}


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'
                ]


find() basically returns MongoDB cursor http://www.php.net/manual/en/mongocollection.find.php

this should work for your case

$cursor = $collection->find();
foreach($cursor as $jokes) {
 print_r($jokes);
}


in case if someone came to here, you can also use toArray method.

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::toArray — Returns an array containing all results for this cursor

$jokes = $collection->find()->toArray();

or :

$jokes = $collection->find();
$jokesArray = $jokes->toArray();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜