Laravel-mongodb: how to use aggregate: $match & $group

Created on 11 Oct 2016  路  2Comments  路  Source: jenssegers/laravel-mongodb

I need to run this.

db.mycollection.aggregate([
{
$match: { name: $input_param }
},{
$group:{
_id: "$name",
total_time: { $sum: '$total_online' },
total_home: { $sum: '$home' },
total_inventory: { $sum: '$inventory' },
total_shop: { $sum: '$shop' },
total_spin: { $sum: '$spin' },
total_lobby_quick: { $sum: '$lobby_quick' },
total_lobby_normal: { $sum: '$lobby_normal' },
total_game: { $sum: '$game' },
}
}
])

How to implement this using jenssegers/laravel-mongodb package?
Thank you!

Most helpful comment

I solve my problem. final code:

return mycollection::raw(function($collection) {
return $collection->aggregate([
['$match' => ['name' => $input_param]],
['$group' => [
'_id' => '$name',
'total_time' => ['$sum' => '$total_online'],
'total_home' => ['$sum' => '$home'],
'total_inventory' => ['$sum' => '$inventory'],
'total_shop' => ['$sum' => '$shop'],
'total_spin' => ['$sum' => '$spin'],
'total_lobby_quick' => ['$sum' => '$lobby_quick'],
'total_lobby_normal' => ['$sum' => '$lobby_normal'],
'total_game' => ['$sum' => '$game'],
]]
]);
});

All 2 comments

I solve my problem. final code:

return mycollection::raw(function($collection) {
return $collection->aggregate([
['$match' => ['name' => $input_param]],
['$group' => [
'_id' => '$name',
'total_time' => ['$sum' => '$total_online'],
'total_home' => ['$sum' => '$home'],
'total_inventory' => ['$sum' => '$inventory'],
'total_shop' => ['$sum' => '$shop'],
'total_spin' => ['$sum' => '$spin'],
'total_lobby_quick' => ['$sum' => '$lobby_quick'],
'total_lobby_normal' => ['$sum' => '$lobby_normal'],
'total_game' => ['$sum' => '$game'],
]]
]);
});

Sweet... When I was trying with groupBy() instead of using raw form, I was continuously getting Call to a member function groupBy() on float error. Thanks for sharing the solution. I come from a CakePHP background. This entire eloquent thing seems terribly confusing to me.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Idnan picture Idnan  路  3Comments

naveedyasin picture naveedyasin  路  3Comments

lgt picture lgt  路  3Comments

bastiendonjon picture bastiendonjon  路  3Comments

HassanIbrahim picture HassanIbrahim  路  3Comments