Get the creation date from MongoDB ObjectIds, build one from a date, and generate _id date-range queries
Read when a document was created from its ObjectId, turn a date into an ObjectId, and get a ready-made _id range query.
How to use it
Paste ObjectIds, one per line, up to 500 lines. ObjectId("…") and {"$oid": "…"} work too. Read each id’s creation time in UTC and in the time zone you pick. Date to ObjectId turns a date and time into an id. For a date range, pick the start and end dates and copy the query for mongosh, Node.js or Python.
Examples
ObjectId to date
Input
507f1f77bcf86cd799439011
Result
2012-10-17T21:13:27.000Z
The first 8 hex characters (507f1f77) are the Unix seconds.
Documents created in January 2024
Input
From 2024-01-01 to 2024-02-01 (UTC)
Result
db.orders.find({
_id: {
$gte: ObjectId("659200800000000000000000"), // 2024-01-01T00:00:00.000Z
$lt: ObjectId("65badf000000000000000000") // 2024-02-01T00:00:00.000Z
}
})What’s inside an ObjectId
| Bytes | Hex chars | Holds |
|---|---|---|
0–3 | 1–8 | Creation time in Unix seconds (big-endian) |
4–8 | 9–18 | Random value, made once per process |
9–11 | 19–24 | Counter, starting at a random value |
Sources: MongoDB ObjectId docs
Why range queries on _id are fast
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. - Can I insert the ObjectId made from a date?
Not as a real id. It holds the time followed by zeros, so every id made for the same second is the same one, and a second insert would clash. Use it as a bound in an _id range query; New ObjectId (or your driver) makes unique ones. The code under the query writes both helpers for mongosh, Node.js and Python. - Is the ObjectId time reliable?
It is the clock of the machine that generated the id, usually the app server’s driver, to the second. If the app creates the id well before the insert, or that clock is wrong, the time differs from the real insert time. - Are my ids uploaded?
No. Everything runs in your browser, so your ids stay on your device. Nothing you paste is uploaded unless you share it. Decoding is plain arithmetic, with no database connection.