2011-03-19 109 views
6

如何在find()之後查看並「執行」MongoDB集合中的內容?即:如何在PHP中打印MongoDB集合?

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

等。無論我做什麼,我什麼也得不到,但如果我循環它,我可以通過一個獲取數據出來一個我能出得到的數據(當然),但問題是,我想要用它做事情,比如將返回的數組整體編碼爲用於執行AJAX/JS的JSON對象。

那麼,我該怎麼做呢?

回答

4

標準是循環遍歷結果,使用foreach或while。

還有(作爲PHP版本> 5.1的一部分),iterator_to_array,它可以與Mongo遊標一起使用。正如Mongo::find上的註釋,這會將所有結果加載到內存中, 可能會超出內存限制並使腳本崩潰 - 因此請注意預計有多少數據。

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

這個:https://gist.github.com/a1cceb8d4ec8ced1fbdb - 是我現在怎麼做...它似乎凌亂:\ – 2011-03-19 22:00:48

4

你正在嘗試做的的print_r在MongoCursor,而不是一個PHP數組(這是行不通的。)

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

你需要任何轉換光標到一個PHP數組...

<? 
// 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>"; 
} 
?> 

或者,使用findOne(),而不是返回一個MongoCursor ...所以如果你只是想得到一個文件和JSON返回到您的應用程序,你可以做到這一點很簡單,像這樣(這表明該怎麼辦JSON和print_r的,你問)...

請參閱以下文章更多的幫助...

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>"; 

?> 
0

使用shell你可以在一個方式查詢蒙戈,它將輸出的結果作爲數組。

db.products.find().toArray() 

以上將打印作爲數組格式的集合「產品」。我還沒有測試,但你可能能夠用PHP獲得輸出並進行打印。只是一個想法。