2017-08-13 35 views
0

我用這個代碼來獲得在PHP如何獲取MongoDB PHP中的特定字段?

$client = new MongoDB\Client("mongodb://localhost:27017"); 
$collection = $client->test->users; 
$result = $collection->find(array(), array('name' => 1, '_id' => 1)); 

特定的領域,但它返回的所有字段。
我從這個鏈接的最後一行:
http://php.net/manual/en/mongo.sqltomongo.php

數據:

object(MongoDB\Model\BSONDocument)#36 (1) { ["storage":"ArrayObject":private]=> array(7) { ["_id"]=> object(MongoDB\BSON\ObjectID)#35 (1) { ["oid"]=> string(24) "598ebdeab318de646ca08788" } ["is_hidden"]=> bool(false) ["priority"]=> int(1) ["picture"]=> string(21) "15025269499885875.jpg" ["__v"]=> int(0) ["name"]=> string(8) "John" } } 

預期結果:

object(MongoDB\Model\BSONDocument)#36 (1) { ["storage":"ArrayObject":private]=> array(7) { ["_id"]=> object(MongoDB\BSON\ObjectID)#35 (1) { ["oid"]=> string(24) "598ebdeab318de646ca08788" } ["name"]=> string(8) "John" } } 
+0

請添加您的數據和所需的結果。 –

+0

數據和期望的結果應添加到您的問題部分而不是評論部分。請更新您的問題並刪除評論@ WithoutBrain1994 –

回答

1

(解決):
最後一行應該是這樣的:

$result = $collection->find(array(), array('projection' => array('name' => 1, '_id' => 1))); 
相關問題