php – 將日期時間轉換為 Mongo ObjectId
最近在 Laravel 開發使用 MongoDB 做時間區間的篩選。
因為 Mongo 預設的 _id 具有時間戳記,因此篩選某個時間區段,可以直接透過 _id 做取得。那問題是,如何把時間轉換為 _id 格式呢?以下程式碼提供參考
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace App\Libraries; use MongoDB\BSON\ObjectId; class MongoDB { /** * 透過指定日期時間,取得 Mongo ObjectId * * @param string $timeString 時間字串,如 2019-01-01 12:52:14 或 2019-01-01 ,只要是時間字串即可 * @return ObjectId 返回 Mongo _id 格式 */ public static function getObjectIdFromTimeString(string $timeString): ObjectId { $timestamp = strtotime($timeString); return new ObjectId(dechex($timestamp) . str_repeat("0", 16)); } } |
那麼 Laravel 就可以這樣比對
1 2 3 4 5 6 7 |
$id = MongoDB::getObjectIdFromTimeString("2020-02-11 11:18:15"); $result = Interview::select("_id") ->where("_id", ">=", $id) ->get(); |