Rez
Rez

Reputation: 524

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

Upvotes: 6

Views: 5961

Answers (1)

Rez
Rez

Reputation: 524

(Solved):
Last line should be this:

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

Upvotes: 10

Related Questions