How do i view and "do" things having a MongoDB collection after find()ing my results? I.e.:

   $cursor = $collection->find();

etc. Regardless of what I actually do i recieve nothing, but when I loop it i'm able to obtain the data out 1 by 1 i'm able to obtain the data out (obviously) however the problem is, I wish to do things by using it like scribe the came back array in general to some JSON object for doing AJAX / JS stuff.

So, how could I actually do this?

The conventional it's to loop within the results, with foreach, or while.

There's also (included in PHP versions > 5.1), iterator_to_array, which may be combined with the Mongo cursors. Because the note on Mongo::find this can load all of the results into memory, that could exceed memory limits and crash the script - so be familiar with just how much information is expected.

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

You are attempting to complete the print_r on the MongoCursor, not really a PHP array (which will not work.)

You will need to either convert the cursor to some 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() rather that won't return a MongoCursor ... therefore if you want to acquire one document and give it back as JSON for your application it can be done pretty simply like so (this shows how you can do JSON and print_r while you requested) ...

See this content for additional help ...


$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>";
echo "</pre>";

echo "<h2>Show result as JSON:</h2>";
echo "<pre>";
echo json_encode($obj);
echo "</pre>";