Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MongoDB\Client not accepting projection in query

I have a documents that contain large amounts of data I don't need for a particular query on a page, and I want to speed up the request. When I perform the following query from the mongo shell:

db.hosts.find({},{dmiSystem: 1, networkInterfaces: 1, lanPrint: 1, pduPorts: 1})"

The mongo shell returns the fields I ask for almost instantly. When I perform this same query from PHP using MongoDB\Client it takes about 5 seconds, the same amount of time as if I just ran a find() without any parameters. Any ideas? My code is:

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->selectCollection("consoleServer", "hosts");
$rows = $collection->find(array(),array("_id" => 1, "dmiSystem" => 1,
                          "networkInterfaces" => 1, "lanPrint" => 1,
                          "pduPorts" => 1));
return $rows;
like image 363
Craig Jackson Avatar asked Aug 05 '26 00:08

Craig Jackson


2 Answers

Find method needs 2 arrays. @Henkealg's answer has syntax error.

This is correct way to set projection and eg. limit:

$cursor = $collection->find(
    [],
    [
        'limit' => 5,
        'projection' => [
            '_id' => 1,
        ]
    ]
);

Be aware that you won't get error if you have typing error. Eg projction instead of projection.

like image 139
seven Avatar answered Aug 06 '26 14:08

seven


The new MongoDB library for PHP uses another query syntax that looks more similar to Mongo Shell, using a projection variable.

Based in your example, you should be able to use something like this:

$rows = $collection->find(
      array(),
        'projection' => array(
           array(
             "_id" => 1, 
             "dmiSystem" => 1,
             "networkInterfaces" => 1, 
             "lanPrint" => 1,
             "pduPorts" => 1)
        )
    );

More information is available in the Mongodb docs.

like image 38
Henkealg Avatar answered Aug 06 '26 14:08

Henkealg