8

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?

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Lê Gia Lễ
  • 450
  • 3
  • 12
  • 23
  • Possible duplicate of [Mongodb: Perform a Date range query from the ObjectId in the mongo shell](https://stackoverflow.com/questions/13593896/mongodb-perform-a-date-range-query-from-the-objectid-in-the-mongo-shell) – Mohammed Essehemy Sep 23 '17 at 11:22
  • No that is a different answer, this is if we want to convert a timestamp to objectID where you want the objectID to contain a certain date/time, not necessarily the current datetime – Sharjeel Ahmed Nov 13 '17 at 14:16

4 Answers4

14

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.

vkrishna
  • 644
  • 1
  • 6
  • 10
5

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)
Derek Hill
  • 5,077
  • 2
  • 52
  • 68
0

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.

Pratik Gujarathi
  • 891
  • 1
  • 10
  • 18
0

Yes you can:

dummy_id = ObjectId.from_datetime(gen_time)

Where gen_time is datetime.

svink
  • 61
  • 1
  • 8