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" } }
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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).
You can extract the value of a field by appending that field's name to your query when using findOne() .
(Solved):
Last line should be this:
$result = $collection->find(array(), array('projection' => array('name' => 1, '_id' => 1)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With