jenssegers/laravel-mongodb — pull request #340 by mitulgolakiya (2014-10-10 09:10:29+00:00)
Title: Aggregation problem with $limit

If we use $limit with aggregation stuff, say sum, avg or anything else. Then it creates a problem in results. I have a database of orders, where I want to retrieve a sum of last 10 transactions of one particular customer.
Here is my query.
```
$value = Order::where('cust_id', 1)->take(10)->orderBy('orderDate', 'desc')->sum('amount');
```
Then $pipeline object is created like this:
```
Array(
[0] => Array(
[$match] => Array(
[$and] => Array(
[0] => Array(
[cust_id] => 1
)
[1] => Array(
[product_id] => 1
)
)
)
)
[1] => Array(
[$group] => Array(
[_id] => null
[aggregate] => Array(
[$sum] => $amount
)
)
)
[2] => Array(
[$sort] => Array(
[orderDate] => -1
)
)
[3] => Array(
[$limit] => 10
)
)
```
So what it does is, it first matches all orders of customer with particular product, then it creates sum of amount of all those orders and then it applies sort, skip and limit params. So it gives me the sum of amount of all orders, not for last 10 orders.

So I think $group should be come after all these three params. And query should be,
```
Array(
[0] => Array(
[$match] => Array(
[$and] => Array(
[0] => Array(
[cust_id] => 1
)
[1] => Array(
[product_id] => 1
)
)
)
)
[1] => Array(
[$sort] => Array(
[orderDate] => -1
)
)
[2] => Array(
[$limit] => 10
)
[3] => Array(
[$group] => Array(
[_id] =>
[aggregate] => Array(
[$sum] => $amount
)
)
)
)
```
If I run this query with pure native MongoClient then it gives me proper result.