Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from Timestamp to Mongo ObjectID

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?

like image 301
Lê Gia Lễ Avatar asked Jul 28 '16 07:07

Lê Gia Lễ


Video Answer


2 Answers

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.

like image 152
vkrishna Avatar answered Oct 19 '22 12:10

vkrishna


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)
like image 27
Derek Hill Avatar answered Oct 19 '22 12:10

Derek Hill