如何在 laravel mongodb jenssegers 中获取子文档大小(计数)

How to get sub-document size (count) in laravel mongodb jenssegers

我想获取评论数而不是在单个查询中获取所有评论, 我正在使用以下代码但出现错误

$answers = Answers::project([
    'comments'=>0, 
    'comments_count' => [
        '$size' => '$comments'
    ]])
    ->where('question_id',$request->question_id)
    ->get();

错误:- "message":"Unsupported projection option: comments_count: { $size: \"评论\" }",

jenssegers mongodb laravel 包中是否支持 $size 聚合? 如果是,那么这就是正确的使用方法,

谢谢。

取决于本文 https://laravel.com/docs/5.7/eloquent-relationships 你可以使用 withCount

Project 模型中你可以添加 protected 变量 withCount

protected $withCount = ['comments'];
//comments is function name of relation between project and comments

将returncomments_count

你可以运行一个带有聚合的原始查询,检查下面的查询

$answers = Answers::raw(function($collection) use ($request) {
            return $collection->aggregate([
                [
                    '$match' => [
                        'question_id' => $request->question_id
                    ]
                ],
                [
                    '$project' => [
                        'answer'=>1,
                        'user'=>1,
                        'comment_count' => [
                            '$size' => [ 
                                '$ifNull'=> ['$comments', []] 
                            ] 
                        ]
                    ]
                ]
            ]);
        });

这是 laravel 5.6 中使用 jensseger mongodb 的有效查询。