Create MongoDB ObjectID from date in the past using PHP driver

后端 未结 3 897
别那么骄傲
别那么骄傲 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:38

    Right now, the PHP driver has no built in functionality for this, the __set_state() that the other answer mentioned is only for being able to session-deserialize the ID and doesn't allow you to create it through the specific components.

    You will have to do the following to automatically create an ID:

    <?php
    function createId( $yourTimestamp )
    {
        static $inc = 0;
    
        $ts = pack( 'N', $yourTimestamp );
        $m = substr( md5( gethostname()), 0, 3 );
        $pid = pack( 'n', posix_getpid() );
        $trail = substr( pack( 'N', $inc++ ), 1, 3);
    
        $bin = sprintf("%s%s%s%s", $ts, $m, $pid, $trail);
    
        $id = '';
        for ($i = 0; $i < 12; $i++ )
        {
            $id .= sprintf("%02X", ord($bin[$i]));
        }
        return new MongoID($id);
    }
    
    var_dump( createId( time() ) );
    ?>
    
    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2020-12-17 03:01

    This could create problems since one of the factors that makes the objectid unique is the time part however it should increment the last byte (or so) on multiple inserts with the same time.

    It looks like there was some movement towards allowing a ObjectId to be created with some params and infact it kinda almost talks about it here: http://php.net/manual/en/mongoid.set-state.php

    Theoretically, an array of properties used to create the new id. However, as MongoId instances have no properties, this is not used.

    However there is no way, atm, I believe to achieve what you can do in other languages without writing your own ObjectId generator.

    0 讨论(0)
提交回复
热议问题