How to convert from Timestamp to Mongo ObjectID

13,684

Solution 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.

Solution 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)
Share:
13,684
Lê Gia Lễ
Author by

Lê Gia Lễ

"If you see scary things, look for the helpers-you'll always see people helping."-Fred Rogers

Updated on June 27, 2022

Comments

  • Lê Gia Lễ
    Lê Gia Lễ almost 2 years

    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?

  • asgs
    asgs almost 2 years
    I think from_datetime is PyMongo equivalent, so it won't work in MongoDB shell. the answer from vkrishna mentions the fromDate method