WithoutBrain1994 WithoutBrain1994 - 1 year ago 80
PHP Question

How to get specific fields in MongoDB PHP?

I use this code to get a specific field in php

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


But it returns all fields.

I get the last line from this link:

http://php.net/manual/en/mongo.sqltomongo.php

Data:

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" } }


Expected result:

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" } }

Answer Source

(Solved):
Last line should be this:

$result = $collection->find(array(), array('projection' => array('name' => 1, '_id' => 1)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download