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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器