Laravel mongoDB group by combine with where in

Laravel mongoDB group by combine with where in

这是我当前的代码

    $results = Post::whereIn('category_id', $category_ids)
        ->raw(function($collection) {
            return $collection->aggregate([
                [   
                    '$group' => [
                        '_id' => '$user_id',
                        'count' => [
                            '$sum' => 1
                        ]   
                    ]   
                ],  
                [   
                    '$sort' => [
                        'count' => -1
                    ]   
                ],  
                [   
                    '$limit' => 10
                ],  
            ]); 
        });

我正在尝试获取与特定类别链接的帖子,但是 $results return 所有帖子。

如何修改成where in + group by?

编辑 (2016-07-14 10:13am)

类别

{
    "_id": ObjectID("578489618a8920afcb3f4de2"),
    "updated_at": ISODate("2016-07-13T06:21:40.700Z"),
    "created_at": ISODate("2016-07-12T07:16:49.913Z"),
}

Post

{
    "_id": ObjectID("578499629a89202fcb3f4de3"),
    "user_id": "578299629989e02fcb3f4de3",
    "title": "How to deal with MongoDB",
    "category_id": "578489618a8920afcb3f4de2",
    "updated_at": ISODate("2016-07-12T07:16:50.512Z"),
    "created_at": ISODate("2016-07-12T07:16:50.512Z")
}

{
    "_id": ObjectID("578499629a89202fcb3f4de3"),
    "user_id": "578299629989e02fcb3f4de3",
    "title": "It's so weird~",
    "category_id": "578489618a8920afcb3f4de2",
    "updated_at": ISODate("2016-07-12T07:16:50.512Z"),
    "created_at": ISODate("2016-07-12T07:16:50.512Z")
}

所以1 类别有多个帖子,我想列出每个用户有多少帖子,并按降序排列。

现在分组和排序已经可以工作了,只是不能过滤特定的 category_id

预期输出

| User  | Total posts |
|-------|-------------|
| Smith | 11          |
| Ivy   | 8           |
| Paul  | 3           |

好的,根据你的(奇怪)collections,如果我确实理解得很好,它应该是这样的:

<?php 

$category_ids = []; //categories goes here

$results = Post::raw(function($collection) use ($category_ids) {
    return $collection->aggregate([
        //where in...
        [
            '$match' => [
                'category_id' => ['$in' => $category_ids]
            ]       
        ],  
        [   
            '$group' => [
                '_id' => '$user_id',
                'count' => ['$sum' => 1]   
            ]   
        ],  
        [   
            '$sort' => ['count' => -1]   
        ],  
        [   
            '$limit' => 10
        ],  
    ]); 
});

管道的第一阶段使用 $match$in 来过滤 post.category_id$category_ids 中的帖子。
我应该做这个把戏!