如何在MongoDB PHP中获取特定字段?

时间:2017-08-13 07:46:15

标签: 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" } }

1 个答案:

答案 0 :(得分:3)

(适用解决):
最后一行应该是这样的:

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