感谢@mmroman,我找到了解决方案。它让我尝试了几次让它与 PHP 语法一起工作。这里是。我已经简化了它,希望它可以帮助寻找相同的人。
$pipeline = [ // Github considered wrapping the pipeline in an array like so
[
'$match' => [ // Use match to limit results (better performance)
'comments' => [ '$exists' => true ] // Work only on posts with comments
]
],
[
'$project' => [
'_id' => 1, // 1 = returns field to result, 0 = does not
'id' => 1,
'from' => 1,
'created_time' => 1,
'commentCount' => [ '$size' => '$comments' ] // commentCount can be anything and $comments is the field that has the array you want to count
]
],
[ '$sort' => [ 'commentCount' => - 1 ] ],
[ '$limit' => 5 ] // Limit to the 5 top. You can change this per your satisfaction
];
// Then finally pipe the line to the aggegate
$cursor = $collection->aggregate(
$pipeline
);
希望这对其他人有帮助!
问候,