How to convert from Timestamp to Mongo ObjectID How to convert from Timestamp to Mongo ObjectID mongodb mongodb

How to convert from Timestamp to Mongo ObjectID


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.


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)


Yes you can:

dummy_id = ObjectId.from_datetime(gen_time)

Where gen_time is datetime.