Laravel mongoDB 组通过结合在哪里


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返回所有帖子。

如何将其修改为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"),
}

发布

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

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

<?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的帖子。
我应该做这个伎俩!