How to print_r in PHP MongoDB collection?

How can I browse and “do” things using the MongoDB collection after find() my results? I.e:.

 <?php $cursor = $collection->find(); json_encode($cursor); //OR print_r($cursor); ?> 

etc .. No matter what I do, I get nothing, but if I loop it, I can get the data one by one, I can get the data (of course), but the problem is what I want to do with it something like encoding the returned array as a whole for a JSON object to work with AJAX / JS files.

So how can I do this?

+6
javascript database ajax php mongodb
source share
3 answers

A standard is a loop of results using foreach or while.

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

 $cursor = $collection->find(); $array = iterator_to_array($cursor);. 
+4
source share

You are trying to do print_r on MongoCursor, and not in a PHP array (which will not work.)

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

You 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, instead use findOne (), which will not return MongoCursor ... so if you just want to get one document and return it as JSON in your application, you can do it quite simply like that (it shows how to do JSON and print_r, as you requested) ...

See these articles for more details.

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>"; ?> 
+4
source share

Using the shell, you can query Mongo so that it outputs the result as an array.

 db.products.find().toArray() 

The above document will print a collection of "products" formed as an array. I have not tested, but you can get output with PHP and print. Just a thought.

0
source share

All Articles