[英]how to aggregate mongodb collection data in laravel
i have collection like this 我有这样的集合
{
"wl_total" : 380,
"player_id" : 1241,
"username" : "Robin",
"hand_id" : 292656,
"time" : 1429871584
}
{
"wl_total" : -400,
"player_id" : 1243,
"username" : "a",
"hand_id" : 292656,
"time" : 1429871584
}
as both collection have same hand_id i want to aggregate both these collection on the basis of hand_id i want result as combine of 因为两个集合都有相同的hand_id我想在hand_id的基础上聚合这两个集合我希望结果作为组合
data=array(
'hand_id'=>292656,
'wl_total'=>
{
0=>380,
1=>-400
},
'username'=>
{
0=>"Robin",
1=>"a"
},
"time"=>1429871584
)
You basically want a $group
by the "hand_id" common to all players, and then $push
to different arrays in the document and then also do something with "time", I took $max
. 你基本上想要一个$group
由所有玩家共同的“hand_id”,然后$push
送到文档中的不同数组,然后用“时间”做一些事情,我拿了$max
。 Nees to be an accumulator of some sort at any rate. 无论如何,Nees都是某种累积器 。
Also not sure what your underlying collection name is, but you can call this in laravel with a construct like this: 还不确定你的底层集合名称是什么,但你可以在laravel中用这样的结构调用它:
$result = DB::collection('collection_name')->raw(function($collection)
{
return $collection->aggregate(array(
array(
'$group' => array(
'_id' => '$hand_id',
'wl_total' => array(
'$push' => '$wl_total'
),
'username' => array(
'$push' => '$username'
),
'time' => array(
'$max' => '$time'
)
)
)
));
});
Which returns output ( shown in json ) like this: 哪个返回输出(以json显示),如下所示:
{
"_id" : 292656,
"wl_total" : [
380,
-400
],
"username" : [
"Robin",
"a"
],
"time" : 1429871584
}
Personally I would have gone for a single array with all the infomation in it for the grouped "hand", but I supose you have your reasons why you want it this way. 就个人而言,我会选择一个单独的数组,其中包含所有分组“手”的信息,但是我想你有理由这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.