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 有没有整苹果智能分拣线上图像数据
  • ¥20 有没有人会这个东西的
  • ¥15 cfx考虑调整“enforce system memory limit”参数的设置
  • ¥30 航迹分离,航迹增强,误差分析
  • ¥15 Chrome Manifest扩展引用Ajax-hook库拦截请求失败
  • ¥15 用Ros中的Topic通讯方式控制小乌龟的速度,走矩形;编写订阅器代码
  • ¥15 LLM accuracy检测
  • ¥15 pycharm添加远程解释器报错
  • ¥15 如何让子窗口鼠标滚动独立,不要传递消息给主窗口
  • ¥15 如何能达到用ping0.cc检测成这样?如图