0

I want to fetch comment counts instead of fetching all comments in a single query, The below code I am using but getting the error

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

Error :- "message": "Unsupported projection option: comments_count: { $size: \"comments\" }",

Is $size aggregate support in jenssegers mongodb laravel package? if yes then that is the correct way to use it,

Thanks.

2 Answers2

1

You can run a raw query with aggregate, check below query

$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', []] 
                            ] 
                        ]
                    ]
                ]
            ]);
        });

This is a working query in laravel 5.6 with jensseger mongodb.

-1

depending on this article https://laravel.com/docs/5.7/eloquent-relationships you can use withCount

in Project model you can add protected variable withCount

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

will return comments_count

hossamGamal
  • 161
  • 1
  • 10
  • I did't understand your answer, i am using mongodb with help of jenssegers laravel package and i want all comments count from a sub-document with Eloquent. and Project is not a model in my case its a aggregate function of jessegers package. – Jitendra Suthar Oct 15 '18 at 11:50