Create MongoDB ObjectID from date in the past using PHP driver

后端 未结 3 901
别那么骄傲
别那么骄傲 2020-12-17 02:14

I have to import a lot of data into MongoDB from MySQL and I\'d like to use the timestamp from the ObjectID instead of storing it in a separate key/value (as it is in the ex

3条回答
  •  感情败类
    2020-12-17 02:50

    If you are using the MongoId just for comparison, for example, selecting all records within a date range, you don't need a fully valid id. So you could simply do:

    $id = new \MongoId(dechex($timestamp) . str_repeat("0", 16));
    

    Just be sure to never insert this id and just use it for $gte/$gt/$lt/$lte queries.

    edit

    My bad, the above snippet would work with dates before about 1979 as dechex($timestamp) doesn't always return 8 characters, so a better snippet would be:

    $id = new \MongoId(sprintf("%08x%016x", $timestamp, 0));
    

提交回复
热议问题