Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query by time in MongoDB with PHP?

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?

like image 435
jwchang Avatar asked Sep 24 '11 12:09

jwchang


People also ask

Can I use PHP with MongoDB?

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.

How is datetime stored in MongoDB?

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.

How do I query data in MongoDB?

To query data from MongoDB collection, you need to use MongoDB's find() method.

What is ISODate in MongoDB?

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.


2 Answers

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 );
like image 136
jwchang Avatar answered Sep 28 '22 00:09

jwchang


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.

like image 24
hakre Avatar answered Sep 28 '22 00:09

hakre