How i can return specified fields in mongodb find(

2019-09-16 18:14发布

问题:

I try:

$fields = array('name'=>true);
find (array(array(), $fields))

but it's not working (I get nothing) and I can't see my mistake. Sorry :(

回答1:

If you use mongodb/mongodb php composer package, you need to specify projection option:

find([], ['projection' => ['name' => false]])

Another example of options:

find([], ['limit' => 5, projection' => ['name' => false], ...])


回答2:

The PHP function for find does not work like that. Try:

find(array(), array('name'=>1))

(basically omit the surrounding array)

For reference here is the documentation page: http://php.net/manual/en/mongocollection.find.php



回答3:

If you are looking for a specific field in all your records you can do something like this:

$cursor = $collection->find();
    foreach( $cursor->fields(array('myField' => true )) as $doc ) {
        echo "<pre>";
        var_dump($doc);
        echo "</pre>";

This would return only 'myFeild' for each document in the collection.

http://php.net/manual/en/mongocursor.fields.php