开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜