【问题标题】:Get error 'MongoResultException' when use aggregate in mongoDB在 mongoDB 中使用聚合时出现错误“MongoResultException”
【发布时间】:2018-06-07 19:44:48
【问题描述】:

当我在 PHP 中使用aggregate时,我得到错误:

MongoResultException: localhost:27017: 'cursor' 选项是 必需,除了带有解释参数的聚合


我使用 mongoDB 3.6 和 PHP 5.6
请看照片

我的代码:

$dbconn = new MongoClient();

$c = $dbconn->selectDB("test")->selectCollection("users");

$ops = array(
    array(
        '$lookup' => array(
          'from'      => 'news',
          'localField'  => '_id',
          'foreignField'  => 'user_id',
          'as'      => 'user_docs'
        )
    )
);

$results = $c->aggregate($ops);
var_dump($results);

【问题讨论】:

    标签: php mongodb


    【解决方案1】:

    对于可能遇到相同问题的其他人,这里是解决方案。

    聚合器命令在 3.6 版本中进行了修改,如文档中所示:

    Changed in version 3.4: MongoDB 3.6 removes the use of aggregate command without the cursor option unless the command includes the explain option. Unless you include the explain option, you must specify the cursor option.

    在 Mongo 中,您可以只添加光标选项而不指定任何参数,如文档中所述:

    cursor: {}
    

    在 PHP 中,您需要像这样指定选项,new stdClass() 对应于 Mongo 中的空对象“{}”:

    $results = $c->aggregate($ops, ['cursor' => new \stdClass()]);
    

    以下是您的示例的操作方法:

    $dbconn = new MongoClient();
    
    $c = $dbconn->selectDB("test")->selectCollection("users");
    
    $ops = array(
        array(
            '$lookup' => array(
              'from'      => 'news',
              'localField'  => '_id',
              'foreignField'  => 'user_id',
              'as'      => 'user_docs'
            )
        )
    );
    
    $results = $c->aggregate($ops, ['cursor' => new \stdClass()]);
    var_dump($results);
    

    如果你想利用调用'cursor'来添加参数,比如batchSize,你可以这样做:

    $results = $c->aggregate($ops, ['cursor' => ['batchSize' => 200]]);
    

    所有参数都列在上面链接的文档页面中。

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 1970-01-01
      • 2023-01-16
      • 2020-04-21
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 2021-12-06
      • 2021-12-14
      相关资源
      最近更新 更多