如何对嵌入文档执行聚合查询?

时间:2016-10-18 12:46:17

标签: php mongodb laravel mongodb-query aggregation-framework

我在laravel应用程序中使用jenssegers / laravel-mongodb库但是我需要显示嵌入文档的计数。使用评论/帖子的通用示例,虽然我可以通过拉动所有帖子并循环来获取评论来计算它们来解决我的问题,但我只是不确定我是否可以查询它们。

我确实建立了自己的人际关系。在我的课程中,我做了:

 public function comments()
    {
        return $this->hasMany('App\Comment');
    }

在我的评论课中:

 public function post()
        {
            return $this->belongsTo('App\Post');
        }

稍后在代码中:

 $post->comments()->save($comment);
 $comment->post()->associate($post);

我的文档结构:

"posts" : [ 
{
    "_id" : ObjectId("5805a11e2594ee26543ea041"),
    "Post_Num" : "166236001010",
    "updated_at" : ISODate("2016-10-18T04:12:14.454Z"),
    "created_at" : ISODate("2016-10-18T04:12:14.451Z"),
    "comments" : [ 
        {   
            "Comment_Num" : "3333333",
            "_id" : ObjectId("5805a11e2594ee26543ea042"),
            "post_id" : "5805a11e2594ee26543ea041",
        },
        {   
            "Comment_Num" : "3333333",
            "_id" : ObjectId("5805a11e2594ee26543ea042"),
            "post_id" : "5805a11e2594ee26543ea041",
        }
    ]

},

{
    "_id" : ObjectId("5805a11e2594ee26543ea041"),
    "Post_Num" : "166236001010",
    "comments" : [ 
        {   
            "Comment_Num" : "3333333",
            "_id" : ObjectId("5805a11e2594ee26543ea042"),
            "post_id" : "5805a11e2594ee26543ea041",
        }
    ]

}
]

现在,当我尝试收到如下评论时:

$post->comments()->count() 
or
$post->comments()->get()->count() 
or
$post->comments->get()->count() 

我得到0.如果它不是嵌入式文档但是只是想知道是否可以进行聚合查询,那么相同的逻辑是有效的吗?也许最好让代码迭代并添加一切?

你可以说我需要一些小手握。谢谢

更新:我正在尝试以下

 public function commentCount()
    {

        $commentsCount = Post::raw(function($collection)
        {

            return $collection->aggregate(['$project' => ['_id' => 1,
                'comments_count' => ['$size' => '$comments']],
                ['$group' => ['_id' => null, 'count' => ['$sum' => '$comments_count']]]]);

        });
        return $commentsCount;
    }

我现在得到的是:

$pipeline is not a list (unexpected index: "$project") 

1 个答案:

答案 0 :(得分:1)

为了清楚起见,您想要一个帖子列表,其中包含每篇帖子的评论数量?

聚合可以为此提供: https://docs.mongodb.com/manual/reference/operator/aggregation/size/#exp._S_size

我不是一个php dev,但这是我的镜头:

Post::raw()->aggregate(
    ['$project' => ['_id' => 1,
                    'Post_Num' => 1,
                    'comments_count' => ['$size' => '$comments']],
    ['$group' => ['_id' => null, 'count' => ['$sum' => '$comments_count']]]
]);