Reputation: 509
I am working on laravel 5.1 and using jessenger mongodb package. I am using raw query to fetch data but i am confused how to use date with that as currently it is returning null result.
$resultSet = DB::connection('mongodb')->collection('wc_mycollection')->raw(function ($collection){
return $collection->aggregate([
[
'$match'=>[
'created_at'=>[
'$gte' => Previous day midnight,
'$lt' => Current Time
]
]
],
[
'$group' => [
'_id' => '$some_id',
]
]
]);
});
what should i do?
Upvotes: 6
Views: 7391
Reputation: 30074
This worked for me:
$start = new \MongoDB\BSON\UTCDateTime(new \DateTime("-8 days"));
Upvotes: 1
Reputation: 103425
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
)
)
)
));
});
Upvotes: 1
Reputation: 7484
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.
Upvotes: 1