按PHP中的Array Field大小对Mongo DB集合进行排序

时间:2018-02-06 12:40:24

标签: arrays mongodb php-mongodb

这里是MongoDB的新手,我很难实现这一目标。我有一个名为posts的集合数据库。它具有以下结构(以其最简单的形式):

{
    "_id": ObjectId
    "title" : String
    "content" : String
    "comments" : Array
}

将PHP与新的MongoDB驱动程序一起使用,我希望运行一个返回按注释数排列的文档的查询。我使用了以下代码,但我不确定这是否是正确的方法:

$cursor = $collection->find([],
    [
        'sort' => [ 'comments' => - 1 ]
    ]
);

任何帮助将不胜感激!谢谢SO社区!

2 个答案:

答案 0 :(得分:2)

您应该能够使用投影阶段使用汇总框架,该投影阶段使用the $size operator计算评论数量,然后添加sort stage。但是,这可能会非常慢,因为每次查询时都必须计算计数...所以...如果你想要这个,你可能想要预先计算注释的数量并创建一个基于索引的在预先计算的数字上。 有点像:

db.col.aggregate([{$project: ... "numberOfComments" : 
   {$size : "$comments"},
 {$sort : { numberOfComments : -1 }}])

答案 1 :(得分:0)

我找到了解决方案,感谢@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
);

希望这有助于其他人!

此致