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;
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.
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.
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