PHP MongoDB\Client 查询中不接受投影

PHP MongoDB\Client not accepting projection in query

我有一个包含大量数据的文档,我不需要在页面上进行特定查询,我想加快请求速度。当我从 mongo shell:

执行以下查询时
db.hosts.find({},{dmiSystem: 1, networkInterfaces: 1, lanPrint: 1, pduPorts: 1})"

mongo shell returns 我几乎立即要求的字段。当我使用 MongoDB\Client 从 PHP 执行相同的查询时,大约需要 5 秒,这与我只是 运行 一个没有任何参数的 find() 的时间相同。有任何想法吗?我的代码是:

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

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

PHP 的新 MongoDB 库使用另一种看起来更类似于 Mongo Shell 的查询语法,使用投影变量。

根据您的示例,您应该能够使用如下内容:

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

Mongodb docs 中提供了更多信息。

查找方法需要 2 个数组。 @Henkealg的回答有语法错误。

这是设置投影的正确方法,例如。限制:

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

请注意,如果您输入错误,您不会收到错误消息。例如 projction 而不是 projection.