Laravel Mongodb Raw mongo query with date Laravel Mongodb Raw mongo query with date laravel laravel

Laravel Mongodb Raw mongo query with date


Try this option:

'$match'=>[      'created_at'=>[             '$gte' => new Date("2016-10-02T00:00:00.000Z"),             '$lt' => new Date("2016-11-02T00:00:00.000Z")      ]]

See, if that works.


There is a really nice date handling package in laravel called Carbon that you could use with your queries. If you want to get records from start of today, use Carbon's startOfDay() property or to get the previous date midnight, use Carbon::yesterday()->endOfDay().

Joining all of this together you can construct your pipeline as:

$previousDayMidnight = Carbon::yesterday()->endOfDay(); // or $startOfToday = Carbon::now()->startOfDay()$currentTime = Carbon::now();$result = DB::collection('wc_mycollection')->raw(function($collection){    return $collection->aggregate(array(        array(            '$match' => array(                'created_at' => array(                    '$gte' => $previousDayMidnight, // or $startOfToday                    '$lt' => $currentDateTime                )            )        ),        array(            '$group' => array(                '_id' => '$some_id',                'count' => array(                    '$sum' => 1                )            )        )       ));});

Another approach would be to natively use MongoDate objects, you could try

$start = new MongoDate(strtotime(date('Y-m-d H:i:s', '-1 days')));$end = new MongoDate(strtotime(date('Y-m-d H:i:s')));$result = DB::collection('wc_mycollection')->raw(function($collection)    {        return $collection->aggregate(array(            array(                '$match' => array(                    'created_at' => array(                        '$gte' => $start,                         '$lt' => $end                    )                )            ),            array(                '$group' => array(                    '_id' => '$some_id',                    'count' => array(                        '$sum' => 1                    )                )            )           ));    });


This worked for me:

$start = new \MongoDB\BSON\UTCDateTime(new \DateTime("-8 days"));