Skip to content
Sealpaste

MongoDB ObjectId ↔ Timestamp

Read when a document was created from its ObjectId, turn a date into an ObjectId, and get a ready-made _id range query.

ObjectIds (one per line)

Date to ObjectId

Read in UTC. The result is the smallest ObjectId for that second.

Date range query on _id

Pick both dates (midnight in UTC).

How to use it

  1. 1Paste one or more ObjectIds (one per line). ObjectId("…") and {"$oid": "…"} work too.
  2. 2Read each id’s creation time in UTC and your time zone.
  3. 3For a date range, pick the start and end dates and copy the query for mongosh, Node.js or Python.

Private by design

Everything runs in this browser tab. Your input is never uploaded, logged or saved on a server, and there are no public "recent" pages. Close the tab and it's gone.

How we keep it private

Examples

ObjectId to date

The first 8 hex characters (507f1f77) are the Unix seconds.

Input

507f1f77bcf86cd799439011

Output

2012-10-17T21:13:27.000Z
Documents created in January 2024

Input

From 2024-01-01 to 2024-02-01 (UTC)

Output

db.orders.find({
  _id: {
    $gte: ObjectId("659200800000000000000000"),
    $lt: ObjectId("65badf000000000000000000")
  }
})

What’s inside an ObjectId

An ObjectId is 12 bytes, written as 24 hex characters:

BytesHex charsHolds
0–31–8Creation time in Unix seconds (big-endian)
4–89–18Random value, unique per machine and process
9–1119–24Counter, starting at a random value

Sources: MongoDB ObjectId docs

Why range queries on _id are fast

Every collection has an index on _id, and ObjectIds grow with time. So "documents created between two dates" can use that index even when there is no createdAt field: build the smallest ObjectId for each boundary (the timestamp followed by zeros) and query with $gte / $lt.

Precision is one second, and the time is when the driver created the id, which is usually the insert time.

Frequently asked questions

Can I get the creation time in mongosh directly?

Yes: ObjectId("…").getTimestamp() returns the date. In Node.js it is new ObjectId(id).getTimestamp(); in Python, ObjectId(id).generation_time.

Is the ObjectId time reliable?

It is the clock of the machine that generated the id (usually the app server), with one-second precision. If ids are created by the application earlier than the insert, or clocks drift, it can differ slightly from the real insert time.

Are my ids sent anywhere?

No. Decoding is plain arithmetic in your browser; no database connection and no upload.