How can I view and "do" things with a MongoDB collection after find()
ing 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 out one by one i can get the data out (of course) but the issue is, I want to do things with it like encode the returned array as a whole to a JSON object for doing AJAX /开发者_运维知识库 JS stuff.
So, how could I do this?
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.
精彩评论