How to convert from Timestamp to Mongo ObjectID

徘徊边缘 提交于 2020-01-15 04:27:49

问题


I know that we can use getTimestamp() to retrieve the timestamp from the ObjectId, but is there any way to generate an ObjectId from a timestamp?

More specifically, if I have an input of month and year, then I want to convert it into Mongo ObjectID to query in db, how should I do this?


回答1:


try this,

> ObjectId("5a682326bf8380e6e6584ba5").getTimestamp()
ISODate("2018-01-24T06:09:42Z")
> ObjectId.fromDate(ISODate("2018-01-24T06:09:42Z"))
ObjectId("5a6823260000000000000000")

Works from mongo shell.




回答2:


If you pass a number to the bson ObjectId constructor it will take that as a timestamp and pass it to the generate method.

You can get a Date from a month and year per this answer (months start at zero).

So:

timestamp = ~~(new Date(2016, 11, 17) / 1000)
new ObjectId(timestamp)



回答3:


An ObjectId() is a 12-byte BSON type and consists of:

  • The first 4 bytes representing the seconds since the unix epoch
  • The next 3 bytes are the machine identifier
  • The next 2 bytes consists of process id
  • The last 3 bytes are a random counter value

Clearly, you will not be able to create ObjectId() only from timestamp.




回答4:


I've found a solution for this and it works well sofar.

 public function createMongoIdFromTimestamp($timestamp) {
    $inc = 0;
    $ts = pack('N', $timestamp);
    $m = substr(md5(gethostname()), 0, 3);
    $pid = pack('n', getmypid());
    $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);
}



回答5:


Yes you can:

dummy_id = ObjectId.from_datetime(gen_time)

Where gen_time is datetime.



来源:https://stackoverflow.com/questions/38629868/how-to-convert-from-timestamp-to-mongo-objectid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!