Search code examples
mongodblaravelphp-mongodbjenssegers-mongodb

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


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.


Solution

  • 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.