select sum column and group by with Mongodb and Laravel

混江龙づ霸主 提交于 2019-12-02 07:33:26

http://laravel.io/forum/10-05-2014-raw-select-using-jenssegers-laravel-mongodb

check link above or use this as i write.

$total = DB::table('user_info')->sum('amount')->groupBy('user_id')->get();

For better performance use the underlying MongoDB driver's aggregation framework methods as this uses the native code on the MongoDB server rather than the .groupBy() methods which basically wraps mapReduce methods.

Consider the following aggregation operation which uses the $group pipeline and the $sum operator to do the sum aggregation:

db.collectionName.aggregate([
    {
        "$group": {
            "_id": "$user_id",
            "user_info": { "$first": "$user_info" },
            "total": { "$sum": "$amount" }
        }
    }
]);

The equivalent Laravel example implementation:

$postedJobs = DB::collection('collectionName')->raw(function($collection) {
    return $collection->aggregate(array(
        array(
            "$group" => array(
                "_id" => "$user_id",
                "user_info" => array("$first" => "$user_info")
                "total" => array("$sum" => "$amount")
            )
        )   
    ));
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!