2016-09-30 34 views
1

我有一個文檔包含大量數據,我不需要在頁面上進行特定查詢,並且我想加快請求速度。當我從mongo shell執行以下查詢時:PHP MongoDB Client不支持在查詢中投影

db.hosts.find({},{dmiSystem: 1, networkInterfaces: 1, lanPrint: 1, pduPorts: 1})" 

mongo shell幾乎立即返回我要求的字段。當我使用MongoDB \ Client從PHP執行相同的查詢時,大約需要5秒鐘的時間,就像運行find()而沒有任何參數一樣。有任何想法嗎?我的代碼是:

$client = new MongoDB\Client("mongodb://localhost:27017"); 
$collection = $client->selectCollection("consoleServer", "hosts"); 
$rows = $collection->find(array(),array("_id" => 1, "dmiSystem" => 1, 
          "networkInterfaces" => 1, "lanPrint" => 1, 
          "pduPorts" => 1)); 
return $rows; 

感謝幫助。謝謝!

回答

0

新的MongoDB庫PHP使用另一種查詢語法,看起來更類似於蒙戈殼牌,用投影變量。

根據你的榜樣,你應該能夠使用這樣的事情:

$rows = $collection->find(
     array(), 
     'projection' => array(
      array(
      "_id" => 1, 
      "dmiSystem" => 1, 
      "networkInterfaces" => 1, 
      "lanPrint" => 1, 
      "pduPorts" => 1) 
     ) 
    ); 

更多信息,在Mongodb docs可用。

+0

「投影」變量是缺少的。在mongo shell中,這在find()函數的第二個參數中是隱含的,但是在PHP中,這需要具有指定了「projection」的另一個級別的關聯數組。現在運作良好。謝謝! –

0

嘗試$rows = $collection->find(array(), array("projection" => array("_id" => 1, dmiSystem" => 1, "networkInterfaces" => 1, "lanPrint" => 1, "pduPorts" => 1)));

+0

請問您可以添加一些細節並正確縮進您的代碼。 :) – surajsn