dongshan2004 2014-08-09 19:12
浏览 61
已采纳

使用聚合将MongoDB查询转换为PHP的问题

I have the following (working) MongoDB query to generate a list of the hashtag count.

db.twitter.aggregate([
    { 
        $group: { 
            _id: "$status.entities.hashtags.text", 
            hashtags: { 
                $addToSet : "$status.entities.hashtags.text" 
            }
        }
    },
    { $unwind : "$hashtags" }, 
    { $unwind : "$hashtags" },
    { $group : { _id : "$hashtags", count: { $sum : 1 } } },
    { $sort : { count : -1, _id : 1 } }
]);

Now I try to convert this query to PHP code (for laravel):

$cursor = DB::collection('twitter')->raw(function($collection)
{
    return $collection->aggregate(array(
        array(
            '$group' => array(
                '_id' => '$status.entities.hashtags.text', 
                'hashtags' => array(
                    '$addToSet' => '$status.entities.hashtags.text',
                ),
            ),
        ),
        array(
            '$unwind' => '$hashtags',
        ),
        array(
            '$unwind' => '$hashtags',
        ),
        array(
            '$group' => array(
                '_id' => '$hashtags', '
                count' => array(
                    '$sum => 1',
                ),
            ),
        ),
        array(
            '$sort' => array(
                'count' => '-1', 
                '_id' => '1',
            ),
        ),
    ));
});

dd($cursor);

What I can derive from the Laravel-MongoDB docs is that the raw query input works the same as in PHP mongodb.

The error returned is this:

MongoResultException (15951)

localhost:27017: exception: the group aggregate field 'count' must be defined as an expression inside an object
  • 写回答

2条回答 默认 最新

  • doumi7854 2014-08-09 19:28
    关注

    Rewrote the array and now it works:

    $cursor = DB::collection('twitter')->raw(function($collection)
    {
        return $collection->aggregate([
            [ 
                '$group' => [ 
                    '_id' => '$status.entities.hashtags.text', 
                    'hashtags' => [
                        '$addToSet' => '$status.entities.hashtags.text'
                    ]
                ]
            ],
            [ '$unwind' => '$hashtags' ], 
            [ '$unwind' => '$hashtags' ],
            [ '$group' => [ '_id' => [ '$toLower' => '$hashtags' ], 'count' => [ '$sum' => 1 ] ] ],
            [ '$sort' => [ 'count' => -1, '_id' => 1 ] ]
        ]);
    });
    

    Just replaced the {} by [] and the : by => and that did the trick!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀