Reputation: 171
I m using Moloquent for mongoDB in my project, my dates is stored in 2015-09-28 03:30:00
format in mongoDB and want to write a query like
select * from table where date(storeddate)='2015-09-28'
and
select * from table where year(storeddate)='2015'
in mongoDB with Moloquent.
Upvotes: 1
Views: 3942
Reputation: 103425
You could use the query builder to take advantage of native MongoDate objects in constructing a date range that you can then use in the query. For example, the following query
select * from users where date(storeddate)='2015-09-28'
can be written as
$start = new MongoDate(strtotime("2015-09-28 00:00:00"));
$end = new MongoDate(strtotime("2015-09-29 00:00:00"));
$users = DB::collection('users')->whereBetween('storeddate', array($start, $end))->get();
Eloquent also supports Carbon or DateTime objects instead of MongoDate objects which will be converted internally to MongoDate objects when saved to the database.
Using the same example as above, if you want to query for records from Users data where a mongodb datetime field storeddate
year part is 2015
select * from users where year(storeddate)='2015'
use Carbon's createFromDate()
property to create the date range that spans a year:
$users = User::whereBetween(
'storeddate', array(
Carbon::createFromDate(2015, 1, 1),
Carbon::createFromDate(2015, 12, 31)
)
)->get();
Upvotes: 2