PHP MongoDB聚合returns空

PHP MongoDB aggregation returns empty

我正在尝试使用 MongoCollection()::aggregate() 对 mongo 数据集进行平均计算,但是函数 returns 是一个 Cursor 对象,我不知道我在做什么我做错了。

这是数据集内容的示例:

{ word : "word", time : 1234, result  : "pass" }

此管道查询在 mongo 控制台中有效:

{"$group" : 
   {"_id" : "$result", 
    "meanTime" : {"$avg" :"$time"}
   }
}

这是我的代码:

    public function  getTimes($fields = array('correct','wrong','pass')){


    $group = ['$group'=> ["_id" => '$result', "meanTime" => ['$avg' =>'$time']]];

    $agg = $this->collection->aggregate(
                    [$group]
                    );
    return $agg;

}
/*
//This is the var_dump on $agg
object(MongoDB\Driver\Cursor)#82 (2) {
["cursor"]=>
array(17) {
["stamp"]=>
int(0)
["is_command"]=>
bool(false)
["sent"]=>
bool(true)
["done"]=>
bool(false)
["end_of_event"]=>
bool(false)
["in_exhaust"]=>
bool(false)
["has_fields"]=>
bool(false)
["query"]=>
object(stdClass)#76 (0) {
}
["fields"]=>
    object(stdClass)#74 (0) {
    }
    ["read_preference"]=>
    array(2) {
    ["mode"]=>
      int(1)
      ["tags"]=>
      array(0) {
    }
    }
    ["flags"]=>
    int(0)
    ["skip"]=>
    int(0)
    ["limit"]=>
    int(0)
    ["count"]=>
    int(2)
    ["batch_size"]=>
    int(0)
    ["ns"]=>
    string(23) "circular.intesavincente"
["current_doc"]=>
    object(stdClass)#83 (2) {
    ["_id"]=>
      string(4) "pass"
["meanTime"]=>
      float(338)
    }
  }
  ["server_id"]=>
  int(1)
}

//This is the json_encode output
{}

*/

我尝试用array()构造和简化[]来编写管道数组,但结果没有改变。我做错了什么?谢谢

您正在对结果 MongoDB\Driver\Cursor 使用 MongoDB 驱动程序和 mongo-php-library I guess. If so the result is such as should be. You could notice [meanTime] field in the result. You just need apply toArray() 方法。 像这样(基于您的初始代码):

<?php
require 'vendor/autoload.php';

class Timer
{
    public $collection;

    public function getTimes()
    {
        $group = [
            '$group' => [
                "_id"      => '$result',
                "meanTime" => [
                    '$avg' => '$time',
                ],
            ],
        ];

        return $this->collection->aggregate([$group]);
    }
}

$timer = new Timer;
$m = new MongoDB\Client();
$db = $m->test;
$timer->collection = $db->so;
$cursor = $timer->getTimes();
$result = $cursor->toArray();
echo var_export($result[0]->bsonSerialize(), false);

//
// stdClass::__set_state(array(
// '_id' => 'pass',
// 'meanTime' => 1234,
//))

您还可以查看库文档以正确使用各种方法。

您可以使用 mongo.so 扩展来查看更清晰的结果,但此扩展现已弃用。