如何在laravel中聚合mongodb集合数据


how to aggregate mongodb collection data in laravel

我有这样的集合

 {
    "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。无论如何都需要成为某种类型的累加器。

也不确定您的底层集合名称是什么,但您可以在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
}

就我个人而言,我会选择一个包含所有信息的单一数组作为分组"hand",但我想你有你想要这样做的原因。