6

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" } }
2
  • please add your data and desired result. Commented Aug 13, 2017 at 7:49
  • data and desired result should be add in your question section not in comment section. please update your question and delete comments @WithoutBrain1994 Commented Aug 13, 2017 at 8:20

1 Answer 1

10

(Solved):
Last line should be this:

$result = $collection->find(array(), array('projection' => array('name' => 1, '_id' => 1)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.