How to print_r in PHP a MongoDB Collection? How to print_r in PHP a MongoDB Collection? database database

How to print_r in PHP a MongoDB Collection?


You are trying to do the print_r on a MongoCursor, not a PHP array (which won't work.)

http://php.net/manual/en/class.mongocursor.php

You'll need to either convert the cursor to a PHP array ...

<?// Connect to Mongo and set DB and Collection$mongo = new Mongo();$db = $mongo->twitter;$collection = $db->tweets;// Return a cursor of tweets from MongoDB$cursor = $collection->find();// Convert cursor to an array$array = iterator_to_array($cursor);// Loop and print out tweets ...foreach ($array as $value) {   echo "<p>" . $value[text];   echo " @ <b><i>" . $value[created_at] . "</i></b>";}?>

Or, use findOne() instead which will not return a MongoCursor ... so if you just want to get one document and return it as JSON to your application you can do it pretty simply like so (this shows how to do JSON and print_r as you asked) ...

See these articles for more help ...

http://learnmongo.com/posts/mongodb-php-install-and-connect/

http://learnmongo.com/posts/mongodb-php-twitter-part-1/

<?php$connection = new Mongo();$db = $connection->test;$collection = $db->phptest;$obj = $collection->findOne();echo "<h1>Hello " . $obj["hello"] . "!</h1>";echo "<h2>Show result as an array:</h2>";echo "<pre>";print_r($obj);echo "</pre>";echo "<h2>Show result as JSON:</h2>";echo "<pre>";echo json_encode($obj);echo "</pre>";?>


The standard is is to loop over the results, with foreach, or while.

There is also (as part of PHP versions > 5.1), iterator_to_array, which can be used with the Mongo cursors. As the note on Mongo::find this will load all the results into memory, which could exceed memory limits and crash the script - so be aware of how much data is expected.

$cursor = $collection->find();$array = iterator_to_array($cursor);.


Using the shell you can query Mongo in a way that it will output the result as an array.

db.products.find().toArray()

The above will print the collection "products" formated as an array. I haven't tested but you may be able to get the output with PHP and do a print. Just a thought.