问题
I have a issue with my query:
I want to
SELECT "user_info" with SUM "amount" and GROUP BY "user_id"
I am using Laravel 5 and jenssegers/laravel-mongodb
Thank you so much.
回答1:
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();
回答2:
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")
)
)
));
});
来源:https://stackoverflow.com/questions/37850466/select-sum-column-and-group-by-with-mongodb-and-laravel