Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare date with mongodb iso date in laravel mongodb eloquent query?

I want to get record from data where date is greater than given date. But I am getting problem in comparing date with mongodb iso datetime.

Currently I am getting date in Y-m-d format which I want to compare in query and date in mongodb is in 2015-10-08T08:01:46.000Z format.

like image 875
Tuhin Avatar asked Oct 08 '15 09:10

Tuhin


1 Answers

Laravel's Eloquent supports Carbon/DateTime objects instead of MongoDate objects which will be converted internally to MongoDate objects when saved to the database. You could use this date handling package in laravel called Carbon with your queries.

For example, if you want to query for records from Users data where a mongodb datetime field created_at is greater that a given date, say records from today, use Carbon's startOfDay() property:

$dt = Carbon::now()->startOfDay();
$users = User::where('created_at', '>', $dt)->get();

Similarly, to do a data range query i.e. query for records between a specific month, say October of 2015, use the whereBetween method:

$users = User::whereBetween(
             'created_at', array(
                 Carbon::createFromDate(2015, 10, 1),
                 Carbon::createFromDate(2015, 10, 31)
             )
         )->get();

Another approach would be to use Eloquent which allows you to work with Carbon/DateTime objects instead of MongoDate objects. Example inspired from the docs:

<?php

use Jenssegers\Mongodb\Model as Eloquent;

class User extends Eloquent {

    use SoftDeletingTrait;

    /**
     * Collection for Model
     *
     * @var String
     */
    protected $collection = "users";

    /**
     * Connection for model
     *
     * @var type
     */
    protected $connection = 'mongodb';

    protected $dates = array('created_at');
}

Which allows you to execute queries like:

$users = User::where('created_at', '>', new DateTime('-1 day'))->get();

Or natively using MongoDate objects, you could try

$start = new MongoDate(strtotime("2015-10-01 00:00:00"));
$stop = new MongoDate(strtotime("2015-10-31 00:00:00"));

$users = DB::collection('users')->whereBetween('created_at', array($start, $stop))->get();
like image 122
chridam Avatar answered Oct 25 '22 02:10

chridam