通过 Laravel MongoDB 获取每组的最新行

Get latest row of each group by with Laravel MongoDB

我在 MongoDB 中有一个名为 gps 的 table,看起来像这样:


| id | asset_id | coordinates | created_at |
--------------------------------------------
| 1  | 11       | 23,-26      | 2018-11-05 |
| 2  | 22       | 33,-36      | 2018-10-04 |
| 3  | 33       | 23,-27      | 2018-11-01 |
| 4  | 33       | 31,-26      | 2018-10-05 |
| 5  | 11       | 23,-46      | 2018-11-02 |
| 6  | 22       | 32,-21      | 2018-11-01 |
--------------------------------------------

我正在使用 Laravel 和 Laravel MongoDB Library 来构建查询。

我的目标是像 only it will have to make use of the Laravel MongoDB Library mentioned earlier. Another example I tried looking at was this post.

中那样使用 group by 子句获取每个资产的最新坐标

基本上我应该把这个还给我:


| id | asset_id | coordinates | created_at |
--------------------------------------------
| 1  | 11       | 23,-26      | 2018-11-05 |
| 3  | 33       | 23,-27      | 2018-11-01 |
| 6  | 22       | 32,-21      | 2018-11-01 |
--------------------------------------------

我假设这些示例对我不起作用,因为我无法访问此库的所有 Eloquent 函数,只有一些基本函数以及我无法使用 SQL 我的查询生成器中的语法。

你应该试试这个:

DB::table('gps')->orderBy('created_at','desc')->groupBy('asset_id')->get();

我能够通过使用聚合调用和关注 this post here 来解决我的问题。

这是我最终使用的代码,尽管我认为这不是最 Eloquent 可能的方式:

$result = GPS::raw(function ($collection) {
    return $collection->aggregate([
        [
            '$sort' => [
                'created_at' => -1
            ]
        ],
        [
            '$group' => [
                '_id' => '$asset_id', 
                'gps' => [
                    '$push' => '$$ROOT'
                ]
             ]
        ],
        [
            '$replaceRoot' => [
                'newRoot' => [
                    '$arrayElemAt' => [
                        '$gps', 0
                    ]
                ]
            ]
        ]
    ]);
});