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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With