首页 文章

PHP MongoDB - 不推荐使用不带游标选项的aggregate命令 . 什么?

提问于
浏览
8

我已经更新了mongo,现在在日志中出现以下错误: Use of the aggregate command without the cursor option is deprecated

Mongo says that I should put a second REQUIRED parameter to aggregate function, because my current usage is deprecated.

我目前使用以下代码PHP(现已弃用):

$this->db->{$collection}->aggregate($options);

并返回以下格式:

{"result":[
    {
    "_id":"xxxxxx",
    "update":[
    {
    "firstUpdateTime":xxxxxx,
    "updateTime":xxxxxxx,
    }
    ],
    "media":[
    {
    "xxxx":{ ...

To not use an deprecated code I add the new second parameter (but I do not understand what to put):

$this->db->{$collection}->aggregate($options, array('cursor' => array('batchSize' => 101)));

这会返回相同的信息,但会改变初始结构:

{"cursor":{
"id":{
"value":"xxxxxx"
},
"ns":"xxxxxx.instagram",
"firstBatch":[
{
"_id":"xxxxxx",
"update":[
{
"firstUpdateTime":xxxxxx,
"updateTime":xxxxxx,
}
],
"media":[
{
"xxxxxx":{ ...

更新后,Mongo强迫我改变我读取数据的方式 . 我不明白我应该把第二个参数叫做“游标”...

What should I put in that second parameter? Can I set a default value without altering the structure of results?

Doc:https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/ http://php.net/manual/es/mongocollection.aggregate.php

UPDATE:

如果我在函数中指示光标我不再收到错误 . 但是,如果没有应用解决方案,我会阅读LOG并随机出现警告,我有一个代码,我运行了几次,有时如果它报告上述警告而其他人没有 .

为什么?

5 回答

  • 1

    驱动程序 mongo 已弃用,不支持最新的PHP主要版本(例如PHP 7) .

    名为 mongodb http://php.net/manual/en/set.mongodb.php的新驱动程序

  • 1

    当您向MongoDB查询某些内容并期望结果时,您将拥有一个名为 cursor 的变量,它只是指向您当前读取的文档的指针 . 它就像浏览器中的滚动条 .

    您可以使用值 1 指定应将多少文档读入缓冲区 batchSize .

    当您知道希望阅读的文档数量时,它非常有用 . 当您只需要10个文档时,可以使用 batchSize => 10 在单个网络数据包中获取所有文档 . 指定 batchSize => 5 时,需要更长时间,因为它需要两个网络数据包到数据库才能获得预期的10个文档 .

    使用默认的 batchSize 是安全的 .

    您可以尝试使用 foreach 迭代游标,如文档中的示例所示:http://php.net/manual/en/class.mongocommandcursor.php

    我不确定php.net文档是否与最新版本的MongoDB驱动程序是最新的 .

  • 1

    假设您使用的是最新的MongoDB PHP Library,您应该能够传递 'useCursor' => false 选项(默认为 true ),如doc中所述 .

  • 1

    您必须使用 aggregateCursor ,它仅返回光标行而不是 results .

    就像是

    第一批默认设置为101结果 .

    $cur = $this->db->{$collection}->aggregateCursor($pipeline);
    

    对于后续批次,在聚合光标50上设置batchsize(问题中的第二个参数) . 如果您不使用以下选项,默认将获取大约4 MB .

    $cur->batchSize( 50 );
    

    您现在可以迭代并读取结果以获取所有文档 .

    服务器将在第一次循环迭代时获取初始(第一批)101个文档,然后在102次迭代时获取后续批次,在其余批次上以50为间隔获取,直到您耗尽光标 .

    foreach ( $cur as $result )
    {
       echo $result['_id'], "\n";
    }
    

    要控制第一批的批量大小,可以将 batchSize 指定为游标选项,但通常不需要 .

    $cur = $this->db->{$collection}->aggregateCursor($pipeline, 'cursor' => [ 'batchSize' => 1 ]);
    

    参考:https://derickrethans.nl/aggregation-cursor.html

  • 4

    从最新的MongoDB手册中,聚合操作已更改 .

    没有游标的聚合MongoDB 3.4不推荐使用不带游标选项的aggregate命令,除非管道包含explain选项 . 使用aggregate命令在线返回聚合结果时,请使用默认批处理大小游标{}指定游标选项,或在游标选项游标中指定批处理大小:{batchSize:} .

    您可以通过添加 [ "cursor" => [ "batchSize" => 0 ] ] 为函数调用指定该参数,因为第二个参数将解决此问题 . 参考here .

    您也可以参考此SO question 获取游标参数用法 .

相关问题