2016-03-03 64 views
6

升級到PHP的新Mongo Driver後,我面臨排序和查詢日期的問題。使用MongoDate查詢與UTCDateTime

使用的舊驅動程序:http://php.net/manual/en/class.mongodate.php它以秒爲單位在MongoDate對象中存儲日期。

新驅動程序:http://php.net/manual/en/class.mongodb-bson-utcdatetime.php以不同格式存儲日期並以毫秒爲單位存儲它。

已使用$ gte或$ lte進行查詢無用。例如:

$collection -> find(array('start_date' => array('$gte' => new MongoDate()))); 

$collection -> find(array('start_date' => array('$gte' => new MongoDB\BSON\UTCDateTime()))); 

這兩個不會返回相同的結果。使用所有舊數據,我如何仍然可以安全地使用MongoDate和UTCDateTime查詢?

+0

你能[啓用探查(https://docs.mongodb.org/manual/reference /method/db.setProfilingLevel/)並顯示兩個驅動程序生成的查詢? –

+0

根據文檔,與'MongoDate'不同,'UTCDateTime'必須以毫秒爲單位手動傳遞時間戳,如'new UTCDateTime(round(microtime(true)* 1000));'。這會使您的代碼無效,無法轉載以幫助您解決問題。 – Parziphal

回答

0

您需要通過毫秒,而不是秒的時間,一切都將繼續像以前一樣工作:

$time = time(); 
$cursor = $collection->find(['start_date' => ['$gte' => new MongoDB\BSON\UTCDateTime($time * 1000)]]);