Laravel MongoDB groupby does not work like Laravel MySQL groupby. Cause we can use the aggregate function without doing groupby. But in MongoDB, you have to use groupby if you use an aggregate function in your query. In this blog post, we'll delve into the concept of GroupBy in Laravel when using MongoDB as the database.

In this tutorial, I will show you, how to use groupBy in Mongodb in the Laravel application. So I will show you the Laravel MongoDB group by example with a query.

Let's see the example query of laravel mongodb aggregate:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\SupplierPayment;
use Illuminate\Database\Eloquent\Builder;

class TutorialController extends Controller
{   
    public function index()
    {   
        $startDate = date('Y-m-01');
        $endDate   = date('Y-m-30');

        return SupplierPayment::raw(function ($collection) use ($startDate, $endDate) {
            return $collection->aggregate([
                [
                    '$match' => [
                        'payment_month' => [
                            '$gte' => intval($startDate),
                            '$lte' => intval($endDate),
                        ],
                    ],
                ],
                [
                    '$group' => [
                        '_id' => '$payment_month', // Group by the 'payment_month' field
                        'total_paid' => ['$sum' => '$total_paid'], // Calculate the sum of 'total_paid'
                    ],
                ],
                [
                    '$sort' => [
                        '_id' => -1, // Sort in descending order based on total_paid
                    ],
                ],
            ]);
        })
    }
}

 

Read also: Laravel Global Scopes As Reusable Classes Example

 

Conclusion

In this tutorial, we've explored the integration of Laravel with MongoDB and demonstrated how to use the GroupBy clause to group data efficiently. Leveraging Laravel's expressive syntax and MongoDB's flexibility, developers can build powerful applications with ease. As you continue to explore Laravel and MongoDB, remember to refer to their documentation for any updates or additional features.

Category : #laravel

Tags : #laravel , #laravel query