How to query by time in MongoDB with PHP?

I want to request a collection and get documents created less than 3 hours ago.

$realtime = date("Ymd 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 deliver

$ some_condition

without using the IF statement in PHP?

+6
source share
2 answers

I have found a 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 ); 
+9
source

First, find the time three hours before. Then the request is more than this 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 make some mark timestamp → string → timestamp (as you suggested), and you must name the constants that you use so that they understand what they represent.

+1
source

Source: https://habr.com/ru/post/897968/


All Articles