【问题标题】:PHP MongoDB\Client not accepting projection in queryPHP MongoDB\Client 不接受查询中的投影
【发布时间】:2016-09-30 18:21:18
【问题描述】:

我有一个包含大量数据的文档,我不需要在页面上进行特定查询,并且我想加快请求速度。当我从 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;

【问题讨论】:

    标签: php mongodb projection


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

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

      根据您的示例,您应该可以使用以下内容:

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

      更多信息请访问Mongodb docs

      【讨论】:

      • 缺少“投影”变量。在 mongo shell 中,这隐含在 find() 函数的第二个参数中,但在 PHP 中,这需要另一个级别的关联数组并指定“投影”。现在效果很好。谢谢!
      【解决方案3】:

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

      【讨论】:

      • 能否请您添加更多详细信息并正确缩进您的代码。 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-13
      • 2020-08-31
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多