Search code examples
phpmongodblaraveljenssegers-mongodb

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


I am using Laravel 5.6 with MongoDB using Jenssegers Package

Here I want to get total count using group by a method as we do in Mysql eg.

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

According to docs of the package, in MongoDB we can't use aggregate functions simple as we do in eloquent but instead we have to use raw query with MongoDB syntax.

public static function getUsersByTypeLogin()
{

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

        dd($q);
}

When I do dd(dump and die), I am getting Cursor {#586} as result. So basically how to get/access data in cursor into my laravel application?


Solution

  • I'm using too this package a project. I'm using raw closure method that returns aggregation data.

    For Example:

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

    $data should be your data.

    Can you try above codes?.