2017-08-13 68 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))); 
相关问题