我有这样的收藏
{
"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
}
因为两个集合都有相同的 hand_id 我想根据 hand_id 聚合这两个集合 我想要的结果是
data=array(
'hand_id'=>292656,
'wl_total'=>
{
0=>380,
1=>-400
},
'username'=>
{
0=>"Robin",
1=>"a"
},
"time"=>1429871584
)
最佳答案
你基本上想要一个 $group
通过所有玩家共有的“hand_id”,然后是$push
到文档中的不同数组,然后还对“时间”做一些事情,我使用了 $max
。需要是 accumulator无论如何。
也不确定你的基础集合名称是什么,但你可以在 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'
)
)
)
));
});
返回输出(以 json 格式显示)如下:
{
"_id" : 292656,
"wl_total" : [
380,
-400
],
"username" : [
"Robin",
"a"
],
"time" : 1429871584
}
就个人而言,我会选择一个数组,其中包含分组“手”的所有信息,但我想你有你想要这种方式的原因。
关于php - 如何在 laravel 中聚合 mongodb 集合数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32494633/