如何在 laravel 控制器中访问 MongoDB 游标中返回的数据?

How to access data returned in MongoDB cursor in laravel controller?

我正在使用 Laravel 5.6 和 MongoDB 使用 Jenssegers Package

在这里,我想像在 Mysql 中那样使用 group 方法获取总计数,例如

select latitude,longitude,count(*) as `count` from event_logger group by latitude,longitude

根据包的文档,在 MongoDB 中我们不能像在 eloquent 中那样使用简单的聚合函数,而是必须使用 raw 使用 MongoDB 语法查询。

public static function getUsersByTypeLogin()
{

        $q = self::raw()->aggregate(
            [
                array(
                    '$group'=>array(
                        '_id'=>array(
                            'lat'=>'$latitude',
                            'long'=>'$longitude'
                        ),
                        'count'=>array('$sum'=>1)
                    )
                )
            ]
        );

        dd($q);
}

当我执行 dd(转储和死亡)时,我得到 Cursor {#586} 作为结果。 那么基本上如何将游标中的 get/access 数据导入我的 laravel 应用程序?

使用

foreach ($q as $row) {
    //$row contains data for every row
 }

其中 q 是光标。

我也在用这个包做项目。我正在使用 returns 聚合数据的原始闭包方法。

例如:

$data = YourModel::raw(function($collection)
{
    return $collection->aggregate(
        [
            array(
                '$group'=>array(
                    '_id'=>array(
                        'lat'=>'$latitude',
                        'long'=>'$longitude'
                    ),
                    'count'=>array('$sum'=>1)
                )
            )
        ]
    );
});

$data应该是你的数据。

你能试试上面的代码吗?