Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute aggregate in mongodb in laravel framework

I need to get result of following query in laravel frame work (used jenssegers library)

db.product.aggregate({ $group : {_id : "$catid", total : { $sum : 1}}},
                                {$sort:{total:-1}});

I tried to do this like this

return DB::connection($this - > connection)- > 
          collection($this - > collection) - > aggregate(
        '{ $group : {_id : "$catid", total : { $sum : 1 }}},{$sort:{total:-1}}'');

But it is giving error like "ErrorException Undefined index: aggregate" need to know that how to use mongodb "db.collection.aggregate"

The document of my collection is like this

  {
     "_id": ObjectId("5369d68611fe14ddc5f59ff9"),
     "sku": 123456,
     "productid": 1,
     "name": "name1",
     "catid": 1
 }
like image 447
Lucil Sandaruwan Avatar asked May 08 '14 06:05

Lucil Sandaruwan


People also ask

How aggregation is performed in MongoDB?

In MongoDB, aggregation operations process the data records/documents and return computed results. It collects values from various documents and groups them together and then performs different types of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result.

Is aggregation a framework in MongoDB?

The MongoDB aggregation framework is an extremely powerful set of tools. The processing is done on the server itself which results in less data being sent over the network.

Can we connect MongoDB with laravel?

Can I Use MongoDB With Laravel? Yes! In fact, MongoDB is a great choice for Laravel projects. As we get started with Laravel development using MongoDB, we'll work through an example of how to build a blog application.


1 Answers

You can access the aggregate method on the Jenssegers library via the raw() function.

Here is an example of an aggregate call with group, sort, limit and project. You can adapt it to your needs:

//Perform an aggregate function and get a cursor
$cursor = Data::raw()->aggregate([
    ['$group' =>
        ['_id' => '$name', 'count' => ['$sum' => 1]]
    ],
    ['$sort' => ['count' => -1]],
    ['$limit' => 30],
    ['$project' => ['_id' => 0,
                   'text' => '$_id',
                   'size' => '$count',
                   ]
    ],
]);

//Iterate your cursor
$current = $cursor;
do {
    echo $current; //Process each element
} while (!($current = $cursor->next()));

Note that using the raw() method requires using a cursor because it is a low-level call.

like image 98
adelriosantiago Avatar answered Oct 03 '22 22:10

adelriosantiago