首页 文章

在mongoDB中使用聚合时获取错误'MongoResultException'

提问于
浏览
1

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

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

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

enter image description here

我的代码:

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

1 回答

  • 0

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

    在版本3.6中修改了aggregator命令,如文档中所示:

    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中,您需要指定像这样的选项,对应于Mongo中空对象“{}”的新stdClass():

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

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

相关问题