Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get specific fields in MongoDB PHP?

Tags:

php

mongodb

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" } }
like image 437
RezaT1994 Avatar asked Aug 13 '17 07:08

RezaT1994


People also ask

How do I get only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I find fields in MongoDB?

In MongoDB, we can check the existence of the field in the specified collection using the $exists operator. When the value of $exists operator is set to true, then this operator matches the document that contains the specified field(including the documents where the value of that field is null).

How do I get only values in MongoDB?

You can extract the value of a field by appending that field's name to your query when using findOne() .


1 Answers

(Solved):
Last line should be this:

$result = $collection->find(array(), array('projection' => array('name' => 1, '_id' => 1)));
like image 108
RezaT1994 Avatar answered Sep 28 '22 03:09

RezaT1994