PHP MongoDB客户端不接受查询中的投影


PHP MongoDBClient not accepting projection in query

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

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

mongo shell几乎立即返回我请求的字段。当我使用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;

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

这是设置投影和eg的正确方法。限制:

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

注意,如果你有输入错误,你不会得到错误。例如:用projction代替projection

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

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

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

更多信息请参见Mongodb文档

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