简体   繁体   中英

How to retrieve object from MongoDB collection in PHP ?

My PHP code is something like this ...

<?php
    $dbhost = 'localhost';  
    $dbname = 'test_pranav';  
    $connection = new MongoClient("mongodb://$dbhost");
    $connection->selectDB('test_pranav');
    $collection = $connection->selectCollection('test_pranav', 'posts');
    $testResult = $collection->find();  
    print_r($testResult);
    exit;
?>    

I inserted record manully through PhpMongo UI tool. But when I try to print the contents for same table it gives empty object.

Please let me know where am I wrong ?

$collection->find() return a MongoCursor object which is an iterator. The easiest way to retrieve the results is then :

$cursor = $collection->find();  
print_r(iterator_to_array($cursor));

Complete documentation for MongoDB PHP driver can be found here : http://www.php.net/manual/en/mongo.tutorial.php

This is why:

$connection->selectDB('test_pranav');
$collection = $connection->selectCollection('test_pranav', 'posts');

selectDB returns a MongoDB instance so you need:

$db = $connection->selectDB('test_pranav');
print_r($db->test_pranav->find());

which should then print out a MongoCursor object and as @Guillaume says you then use iterator_to_array() on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM