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

标签 php mongodb laravel mongodb-query aggregation-framework

我有这样的收藏

 {
    "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/

相关文章:

php - Paypal API 更新订单运输公司、订单状态和跟踪号码

java - 如何检索和删除嵌入文档 spring data mongodb

laravel - Laravel Homestead卡在VM登录上

php - Laravel 5.2 使用 Associate 更新 BelongsTo 关系

PHP set_time_limit 有效但返回 false

php - 在 cPanel 中的 Cronjob 上运行 PHP 文件

php - 伊伊 1.1 : how to set custom status code?

ruby-on-rails - mongodb 中的高效下采样

mongodb - Node.js 和 Mongoose,太慢无法将 Schema 定义放在单独的文件中?

php - 使用 where 从 created_at 调用数据时出错