[英]select sum column and group by with Mongodb and Laravel
http://laravel.io/forum/10-05-2014-raw-select-using-jenssegers-laravel-mongodb
檢查上面的鏈接或使用此作為我寫。
$total = DB::table('user_info')->sum('amount')->groupBy('user_id')->get();
為了獲得更好的性能,請使用底層MongoDB驅動程序的聚合框架方法,因為該方法使用MongoDB服務器上的本機代碼,而不是基本包裝mapReduce方法的.groupBy()
方法。
考慮以下使用$group
管道和$sum
運算符進行匯總的匯總操作:
db.collectionName.aggregate([
{
"$group": {
"_id": "$user_id",
"user_info": { "$first": "$user_info" },
"total": { "$sum": "$amount" }
}
}
]);
等效的Laravel示例實現:
$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")
)
)
));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.