如何使用PHP在MongoDB中按时间查询?

Ins*_*dJW 6 php datetime mongodb

我想查询一个集合并获取不到3小时前创建的文档.

$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 );
Run Code Online (Sandbox Code Playgroud)

是否有一种有效的方式

$ some_condition

部分没有在PHP中使用IF语句?

Ins*_*dJW 9

我找到了解决方案.

$diff = 60 * 60 * 3; //3 hours in seconds

$mongotime = New Mongodate(time()-$diff);

$condition = array('time' => array('$lt'=>$mongotime) );

$result = $db->collection->find( $condition );
Run Code Online (Sandbox Code Playgroud)

  • 你对`$ realtime`的计算是浪费的,你可以做`$ mongotime = new MongoDate(time() - $ diff);` (4认同)