Skip to content

Instantly share code, notes, and snippets.

@codepainkiller
Last active August 28, 2018 12:14
Show Gist options
  • Save codepainkiller/949de10f4edc750cb1c4ae9cc1914b10 to your computer and use it in GitHub Desktop.
Save codepainkiller/949de10f4edc750cb1c4ae9cc1914b10 to your computer and use it in GitHub Desktop.
MongoDB Laravel - Group By
<?php
namespace App\Http\Controllers\Admin;
use App\Appointment;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use MongoDB\BSON\UTCDateTime;
class DashboardController extends Controller
{
public function chartAppointments(Request $request)
{
$startDate = Carbon::today()->startOfMonth();
$appointments = Appointment::raw(function ($collection) use ($startDate) {
return $collection->aggregate([
[
'$match' => [
'created_at' => [
'$gte' => new UTCDateTime($startDate->timestamp * 1000)
],
]
],
[
'$group' => [
// '_id' => [
// 'month' => ['$month' => '$created_at'],
// 'day' => ['$dayOfMonth' => '$created_at'],
// 'year' => ['$year' => '$created_at'],
// ],
'_id' => '$date',
'count' => [
'$sum' => 1
]
]
]
]);
})->pluck('count', '_id');
return $appointments;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment