I want to query a collection and get documents which have created less than 3 hours ago.
$realtime = date("Y-m-d H:i:s");
$mongotime = New Mongodate(strtotime($realtime));
$mongotime = $mongotime - 3 hours; //PSEUDOCODE
$some_condition = array('time' => array('$lt'=>$mongotime) );
$result = $db->collection->find( $some_condition );
Is there an effective way to put
$some_condition
part without using IF statement in PHP?
You can add the driver to your application to work with MongoDB in PHP. The MongoDB PHP Driver consists of the two following components: The extension , which provides a low-level API and mainly serves to integrate libmongoc and libbson with PHP.
MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed. Because this is mainly implemented to help coordinate internal processes like replication and sharding, you should probably not use this in your own application's logic.
To query data from MongoDB collection, you need to use MongoDB's find() method.
ISODate() is a helper function that's built into to MongoDB and wraps the native JavaScript Date object. When you use the ISODate() constructor from the Mongo shell, it actually returns a JavaScript Date object.
I have found the solution.
$diff = 60 * 60 * 3; //3 hours in seconds
$mongotime = New Mongodate(time()-$diff);
$condition = array('time' => array('$lt'=>$mongotime) );
$result = $db->collection->find( $condition );
First get the time three hours before now. Then query larger than that time:
define('SECONDS_PER_HOUR', 3600);
$mongotime = New Mongodate(time()-3*SECONDS_PER_HOUR);
$condition = array('time' => array('$lt'=>$mongotime));
$result = $db->collection->find($condition);
There is no need to do some timestamp -> string -> timestamp conversion (as you suggested it) and you should name the constants you use so it's clear what they represent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With