![](/img/trans.png)
[英]How to get collection class object from mongodb/driver/manager in PHP
[英]How to retrieve object from MongoDB collection in PHP ?
我的PHP代碼是這樣的...
<?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;
?>
我通過PhpMongo UI工具手動插入了記錄。 但是,當我嘗試為同一張表打印內容時,它給出了空對象。
請讓我知道我錯了嗎?
$collection->find()
返回一個MongoCursor
對象,它是一個迭代器。 然后,檢索結果的最簡單方法是:
$cursor = $collection->find();
print_r(iterator_to_array($cursor));
可以在以下位置找到有關MongoDB PHP驅動程序的完整文檔: http : //www.php.net/manual/zh/mongo.tutorial.php
這就是為什么:
$connection->selectDB('test_pranav');
$collection = $connection->selectCollection('test_pranav', 'posts');
selectDB
返回一個MongoDB實例,因此您需要:
$db = $connection->selectDB('test_pranav');
print_r($db->test_pranav->find());
然后應該打印出一個MongoCursor
對象,然后按照@Guillaume的說明,在該對象上使用iterator_to_array()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.