12

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
  • 732,580
  • 175
  • 1,330
  • 1,459
Lê Gia Lễ
  • 510
  • 3
  • 10
  • 24
  • 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

19

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
  • 744
  • 1
  • 6
  • 10
  • never understood why the [MongoDB docs](https://www.mongodb.com/docs/v5.0/reference/method/ObjectId/#methods-and-attributes) don't list the `fromDate` function. thank you so much! – asgs Dec 13 '22 at 16:55
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,965
  • 5
  • 55
  • 74
2

Yes you can:

dummy_id = ObjectId.from_datetime(gen_time)

Where gen_time is datetime.

svink
  • 101
  • 1
  • 9
  • 1
    I think `from_datetime` is PyMongo equivalent, so it won't work in MongoDB shell. the [answer from vkrishna](https://stackoverflow.com/questions/38629868/how-to-convert-from-timestamp-to-mongo-objectid#answer-48589096) mentions the `fromDate` method – asgs Jun 10 '22 at 11:28
-3

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
  • 929
  • 1
  • 11
  • 20