Mongo date range query using _id in PHP - php

Being relatively new to mongo, I read in the mongo manual about Optimizing Object IDs.
http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs-Extractinsertiontimesfromidratherthanhavingaseparatetimestampfield.
Going with the recommendation about NOT creating a separate Created_On field, I decided I would later extract out the date from the _id field which is an ObjectID
Now, I have many records all with out a Created_On field.
I am attempting to query for a date range, but am unsure of the syntax:
$start = new MongoDate(strtotime("2012-03-01 00:00:00"));
$end = new MongoDate(strtotime("2012-03-15 00:00:00"));
$collection->find(array('_id' => array('$gt' => $start, '$lte' => $end)));
Always returns 0 results. Although I can query individual records and extract the date from the object.

In PHP, you need to do something like:
function timeToId($ts) {
// turn it into hex
$hexTs = dechex($ts);
// pad it out to 8 chars
$hexTs = str_pad($hexTs, 8, "0", STR_PAD_LEFT);
// make an _id from it
return new MongoId($hexTs."0000000000000000");
}
$start = strtotime("2012-03-01 00:00:00");
$end = strtotime("2012-03-15 00:00:00");
$collection->find(array('_id' => array('$gt' => timeToId($start), '$lte' => timeToId($end))));
Then you can use that to query the _id field.
I wrote a blog post describing the process here: http://www.snailinaturtleneck.com/blog/2011/12/20/querying-for-timestamps-using-objectids/

Related

Mongodb ISODate format comparison not working in PHP

I have a mongodb record like "estdate" : "2016-06-14T06:49:00.000Z" I am writing the following php code to query the time
$from=$start = new MongoDate(strtotime('2016-04-11 00:00:00'));
$to=new MongoDate(strtotime('2016-06-18 00:00:00'));
$filterpatient = array("order.patientinfo.order_id" => $ordertext,"order.orderitem.estdate" => array('$gte' =>$from, '$lte' => $to));
$cursor = $collection->find($filterpatient)->sort(array('_id'=>-1));
But this is giving no result.
If you are using mongodb driver, this might be helpful for you.
$starttime = strtotime("2016-04-11 00:00:00");
$utcstartdatetime = new MongoDB\BSON\UTCDateTime($starttime);
Now use the $utcstartdatetime in your query for time.

Query in Laravel not working against created_at column

I am writing a query in which I want to fetch data against created_at column. But its not working, it does not return anything. I am using Mongodb as database. Created_at column date is in the format "created_at": ISODate("2016-05-11T09:29:33.112Z") and when I fetch it from database it gives me 2016-05-11 09:29:33.
$datetimenow = date('Y-m-d H:i:s');
$data = ChatMessages::where('created_at','<',$datetimenow)->count();
Try using Carbon Package
$now = \Carbon\Carbon::now('Asia/Dubai'); //you can specify your own timezone
$messages = ChatMessages::where('created_at', '<', $now)->get();
dd($messages);
I got the solution, this is the way how I can do this.
$d1 = new MongoDate(strtotime('2016-01-04 23:21:46'));
$d2 = new MongoDate(strtotime('2016-05-09 23:21:46'));
$data = ChatMessages::whereRaw(['created_at' => array('$gt' => $d1, '$lt' => $d2)])->count();

How to query mongodb Date using php

I need to convert this query from php to mongoDB query
$query = "select * from table where data_added like '%data%';
I have date stored in variable
$date = "2013-09-02";
and in my mongo Document the date sorted as :
$dateAdded = new MongoDate(strtotime('2013-09-02 12:21:55'));
I tried
$date = new MongoDate(strtotime("$date"));
$mongo->find(array('date_added'=>array('$lt'=>$date)));
and
$mongo->find(array('date_added'=>$date));
but without success .
so I need to query usin (Y-m-d) not (Y-m-d h:i:s)
so how to use LIKE query for data in mongo
Thanks
You need to do a range query. Create a timestamp, for example using strtotime(), to get the unix timestamp at the start of the day, and another one and the end of the day.
Depending on if you want these two ends inclusive or exclusive, you then use
// Both points/seconds inclusive
->find(array("date" => array('$gte' => $startOfDay, '$lte' => $endOfDay)));
// Both seconds exclusive
->find(array("date" => array('$gt' => $startOfDay, '$lt' => $endOfDay)));
See http://cookbook.mongodb.org/patterns/date_range/

Inserting a date in mongodb

I want to insert a date into a collection.
I use the class MongoDate to create the date object:
$today = new MongoDate(strtotime(date('Y-m-d 00:00:00')));
The problem is that once it is in my collection the date is 2 hours earlier.
For instance, $today here should be 2013-05-28 00:00:00 but once in the database it is 2013-05-27 22:00:00.
I can't resolve this problem by adding 2 hours manually to the timestamp because I use the date in queries.
The local time of the server where Mongo is running is set to the correct time of my country.
That works in the new php version of mongodb:
new MongoDB\BSON\UTCDateTime((new DateTime($today))->getTimestamp()*1000)
$dt = new DateTime(date('Y-m-d'), new DateTimeZone('UTC'));
$ts = $dt->getTimestamp();
$today = new MongoDate($ts);
This is working.
Remove old document and insert
$bill = array(
"_id" => 1,
"name" => "A",
"lastModified" => new MongoDate()
);
$collection->insert($bill);
FYI: If you need date created for your object model.
$date_created = new \MongoDB\BSON\UTCDateTime(time()*1000);

How to get only date from datetime in CodeIgniter?

I have data in MySQL table like :
ID dates value
1 2011-12-18 10:11:12 test1
2 2011-12-18 12:11:12 test2
3 2011-11-18 10:19:11 test3
When I tried to get value in module it not work, I write code like :
$query=$this->db->get_where('datas', array('dates' => date('Y-m-d')));
I need to get data from whole day like get data only from 2011-12-18.
Thanks
Try This:
$date="2018-09-19";
$this->db->select('*');
$this->db->from('tbl_name');
$this->db->where('DATE(date_time_col)', $date);
$query = $this->db->get();
$res= $query->result();
try with $this->db->like();
so it will be
$query=$this->db->like('dates', array('dates' => date('Y-m-d')));
the % will be added automatically
also you have datas as key, and should be dates based on database structure
You can do the following:
In your table, create an int field with the name ts.
When you insert data into this table, use the time() method to insert a timestamp into ts.
$data = array(
'dates' => '<your date value>' ,
'value' => '<your value>' ,
'ts' => time()
);
$this->db->insert('datas', $data);
Then, when querying:
Use the mktime() method to create a timestamp range for the start & end of today.
$start = mktime() - date('h')*3600;
$end = mktime();
$this->db->where('ts >=', $start);
$this->db->where('ts <=', $end);
Make sure you've indexed the ts column. This will also be faster than the above LIKE method on larger datasets.

Categories