How to query by time in MongoDB with PHP?
I want to query a collection and get documents which have create开发者_C百科d 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?
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.
精彩评论