使用PHP驱动程序从过去的日期创建MongoDB ObjectID [英] Create MongoDB ObjectID from date in the past using PHP driver

查看:86
本文介绍了使用PHP驱动程序从过去的日期创建MongoDB ObjectID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从MySQL导入大量数据到MongoDB,我想使用ObjectID的时间戳,而不是将其存储在单独的键/值中(因为它存在于现有数据中).为此,我需要为现有数据创建一个ObjectID,并带有一个过去的日期.我还需要使用PHP驱动程序来执行此操作.我已经读过,在Python,Java和Node.JS中可能有一种方法可以做到这一点,所以我认为在PHP中可能有一种等效的方法.

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 existing data). In order to do this I'd need to create an ObjectID for the existing data with a date from the past. I also need to do this using the PHP driver. I've read that there might be a way to do this in Python, Java and Node.JS so I thought maybe there was an equivalent method in PHP.

如果可能的话-安全吗?这意味着我将出现重复或无效的ObjectID的问题?谢谢.

If this is possible - is it safe to do? Meaning and I going to have issues with duplicate or invalid ObjectIDs? Thanks.

在Node.JS中:

var timestamp = Math.floor(new Date().getTime()/1000);
var objectId = new ObjectID(timestamp);

以下来自:使用时间戳进行排序的MongoDB

在Python中:

gen_time = datetime.datetime(2010, 1, 1)
dummy_id = ObjectId.from_datetime(gen_time)

在Java中:

Date d = new Date(some timestamp in ms);
ObjectId id = new ObjectId(d)

推荐答案

目前,PHP驱动程序没有为此内置的功能,__set_state()提到的其他答案仅是为了能够对会话进行反序列化. ID,并且不允许您通过特定的组件进行创建.

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.

您必须执行以下操作才能自动创建ID:

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() ) );
?>

这篇关于使用PHP驱动程序从过去的日期创建MongoDB ObjectID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆