1

I'm using the https://github.com/jenssegers/laravel-mongodb library to work with mongodb, how can I query for records that belongs to a specific month? or records from today?

1 Answer 1

2

There is a really nice date handling package in laravel called Carbon that you could use with your queries. You could try using whereBetween if you want to query for records between a specific month, say April of 2015 based on a mongodb datetime field created_at:

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

Similarly, to get records from today, use Carbon's startOfDay() property:

$dt = Carbon::now()->startOfDay();
$users = User::where('created_at', '>', $dt)->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-04-01 00:00:00"));
$stop = new MongoDate(strtotime("2015-04-30 00:00:00"));

$users = DB::collection('users')->whereBetween('created_at', array($start, $stop))->get();
Sign up to request clarification or add additional context in comments.

1 Comment

That's a great answer. but is there a way to execute something like MySQL: where DATE_FORMAT(date,'%Y-%m') = '2015-05' or something like that? i don't want to have hours glitch in the future and to use only days (or months)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.