2013-07-15 66 views
1

我試過如下:檢索蒙戈集合列在PHP

$mongo = new Mongo("mongodb://localhost"); 
print_r($mongo); 

$db = $mongo->test; 

// access collection 
$collection = $db->test; 

// execute query 
// retrieve all documents 
print_r($test); 

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

$fields = $cursor->fields(array("summary" => true)); 
print_r($fields); 

輸出是:

Mongo Object ([connected] => 1 [status] => [server:protected] => [persistent:protected] =>) 
MongoCursor Object () 
MongoCursor Object () 

貌似司機和連接工作,但我不能接受她的列收集test in db test

輸出殼客戶端的:

> show dbs 
local (empty) 
test 0.203125GB 
> show collections 
system.indexes 
test 
> 

> db.test.find() 
{ "_id" : ObjectId("51c861eab6a7c3caa2dc51ec"), "name" : "daniel", "randomNumber" : 49 } 
{ "_id" : ObjectId("51c861f4b6a7c3caa2dc51ed"), "name" : "peter", "randomNumber" : 31 } 
{ "_id" : ObjectId("51c861fab6a7c3caa2dc51ee"), "name" : "ines", "randomNumber" : 7 } 
{ "_id" : ObjectId("51c86b19600090465bc233f4"), "name" : "stein", "randomNumber" : 192 } 
{ "_id" : ObjectId("51c86b21600090465bc233f5"), "name" : "ziege", "randomNumber" : 42 } 
{ "_id" : ObjectId("51c86b36600090465bc233f6"), "name" : "title", "randomNumber" : 753 } 

>如何到動態獲取列在PHP?

回答

-1

在$ cursor變量之後嘗試使用foreach。它遍歷遊標結果。

foreach($cursor as $document) { 
var_dump($document); 
} 
+0

這個作品來獲取所有行(適用於'找到()'),我想有沒有辦法讓一個集合中的所有可用不同的領域? – DanFromGermany

+0

看到這個http://stackoverflow.com/questions/5236160/mongo-equivalent-of-sqls-select-distinct – foxtrot

+0

這取得不同的值,但我需要不同的鍵:-( 像在我上面的示例中,我需要「名稱,隨機號碼「作爲結果 – DanFromGermany

0
const HOST = 'localhost'; 
const PORT = 27017; 
const DBNAME = 'test'; 
const COLLECTION = 'test'; 
$connectionString = sprintf('mongodb://%s:%d', HOST, PORT); 

try { 

     $connection = new Mongo($connectionString); 
     $database = $connection->selectDB(DBNAME); 

} catch (MongoConnectionException $e) { 

     throw $e; 

} 
$collection = $database->selectCollection(COLLECTION); 

try{ 
     $query = array(); 
     $specifyKey = array("summary" => true); 
     $cursor = $collection->find($query , $specifyKey); 

}catch(MongoException $e) { 

     die('Failed to find One data '.$e->getMessage()); 

}catch (MongoCursorException $e) { 

    echo "error message: ".$e->getMessage()."\n"; 
    echo "error code: ".$e->getCode()."\n"; 
} 

while ($cursor->hasNext()){ 

    $nextCursor = $cursor->getNext(); 
    //process next cursor 
}