How to compare date with mongodb iso date in larav

2019-06-26 09:39发布

问题:

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.

回答1:

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();


回答2:

The simplest way for you to compare a date is to use Carbon.

For example, if you want to get from Y-m-d,

you can just use this:

$dt = Carbon::createFromDate(2017,11,7);

where 2017 = year, 11 = month, and 7 = day. Replace it according to your needed date.

If you want to get data before current time, you can use

$dt = Carbon::now()

And if you want to get data from the 1st day of current month onwards, you'll just do this:

$dt = Carbon::now()->startOfMonth();

Below is a an example of what I used in my code:

$device_data = DB::connection('mongodb')
->table('MyRecipe')
->where('data_date', '>', $dt)
->select('*')
->get();

I'm using https://github.com/jenssegers/laravel-mongodb to access my Mongo database.