1

I have a issue with my query:

enter image description here

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.

2 Answers 2

3

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();

Sign up to request clarification or add additional context in comments.

1 Comment

Thank Tejas, If i use MYSQL: It like: SELECT user_id, ..., SUM("amount") as total_amount FROM table WHERE ... AND ... GROUP BY user_id; I use your code and it doesn't work with me. I have some problem: - Field "amount" save by STRING type (can not SUM in normal) - Some WHERE in query. Thanks.
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")
            )
        )   
    ));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.