What's Inside a MongoDB ObjectId (and How to Query by Creation Time)
A MongoDB ObjectId is a 12-byte value whose first 4 bytes are a creation timestamp in seconds since the Unix epoch. That means the MongoDB ObjectId timestamp is always available without storing a separate createdAt field: call getTimestamp() to read it, or build an ObjectId from a date and use it as a bound in an _id range query. The catch is that the timestamp has one-second resolution, comes from the client’s clock, and does not guarantee strict ordering between different writers.
The 12-byte layout
An ObjectId is usually shown as 24 hexadecimal characters. Those are 12 bytes split into three parts:
| Bytes | Size | Content |
|---|---|---|
| 0-3 | 4 bytes | Timestamp, seconds since the Unix epoch, big-endian |
| 4-8 | 5 bytes | A random value, generated once per process by the driver |
| 9-11 | 3 bytes | A counter, started at a random value and incremented for each new ObjectId |
Take 6553f1a2a1b2c3d4e5f60718. The first 8 hex characters, 6553f1a2, are the timestamp. The next 10 are the per-process random value. The last 6 are the counter.
Older documentation describes the middle section as a 3-byte machine identifier plus a 2-byte process id. Current specifications use the 5-byte random value instead, so don’t try to extract a host or pid from modern ObjectIds. If you need to know which service wrote a document, store that explicitly.
Two consequences follow from this design:
- Uniqueness comes from the combination of timestamp, per-process random value and counter. Drivers generate ObjectIds locally, with no round trip to the server, which is why you can use them in client code before the insert happens.
- The ObjectId is generated by the driver, on the client, unless you or the server supply one. The embedded time is therefore the client’s clock, not the server’s.
Reading the timestamp in mongosh
getTimestamp() returns a Date in UTC:
const id = ObjectId("6553f1a2a1b2c3d4e5f60718")
id.getTimestamp()
// ISODate("2023-11-14T22:13:22.000Z")
You can also read it for every document in a query, without a stored date field, using $toDate in an aggregation (it accepts an ObjectId):
db.orders.aggregate([
{ $sort: { _id: -1 } },
{ $limit: 5 },
{ $project: { createdAt: { $toDate: "$_id" } } }
])
This is handy for documents that never had a creation date. If you also need to display the date in a local time zone, see Querying Dates in MongoDB: the same UTC rules apply, and $dateToString with a timezone option works on the result.
You can inspect the raw hex yourself too. In JavaScript:
const hex = "6553f1a2a1b2c3d4e5f60718"
new Date(parseInt(hex.substring(0, 8), 16) * 1000)
// 2023-11-14T22:13:22.000Z
Building an ObjectId from a date
To query by creation time, you want the smallest ObjectId that could have been created at a given moment. Take the date in whole seconds, convert it to 8 hex characters, and pad the remaining 16 characters with zeros:
function objectIdFromDate(date) {
const seconds = Math.floor(date.getTime() / 1000)
return ObjectId(seconds.toString(16).padStart(8, "0") + "0000000000000000")
}
objectIdFromDate(new Date("2026-11-01T00:00:00Z"))
Drivers also ship a helper for this. In the Node.js driver and the bson library, ObjectId.createFromTime(seconds) returns an ObjectId with that timestamp and the other bytes zeroed. Check your driver’s documentation for the equivalent; the hex-string approach above works anywhere an ObjectId can be constructed from a 24-character string.
Querying by creation time with an _id range
Every collection has a unique index on _id, so a range on _id is an index range scan and needs no extra index. This is often faster than adding and indexing a createdAt field you didn’t have.
Find everything created in November 2026 (UTC), using a half-open range:
const start = objectIdFromDate(new Date("2026-11-01T00:00:00Z"))
const end = objectIdFromDate(new Date("2026-12-01T00:00:00Z"))
db.orders.find({ _id: { $gte: start, $lt: end } })
Use $gte for the start and $lt for the end. Because the end bound has zeros in the random and counter bytes, it is smaller than every ObjectId created during that second, so documents created exactly at 2026-12-01T00:00:00Z are correctly excluded.
Common variations:
// Last 24 hours
const since = objectIdFromDate(new Date(Date.now() - 24 * 60 * 60 * 1000))
db.orders.find({ _id: { $gte: since } })
// Most recent 20 documents (index-backed, no sort in memory)
db.orders.find().sort({ _id: -1 }).limit(20)
// Count documents created today (UTC)
const midnight = new Date(); midnight.setUTCHours(0, 0, 0, 0)
db.orders.countDocuments({ _id: { $gte: objectIdFromDate(midnight) } })
Verify that the index is used with explain("executionStats"): you should see an IXSCAN on _id_ and totalDocsExamined close to nReturned. Reading MongoDB explain() in Five Minutes walks through that output.
For paging through a large collection, _id also makes a good cursor: remember the last _id you returned and query { _id: { $gt: lastId } } with sort({ _id: 1 }). That avoids the growing cost of skip.
Limits you should know about
Ordering is only roughly chronological
Sorting by _id orders by timestamp first, then by the random value, then by the counter. Within one process, ObjectIds increase monotonically (until the 3-byte counter wraps, which takes over 16 million IDs in a single second). Across different processes or machines, two ObjectIds created in the same second are ordered by their random bytes, not by actual creation order. So:
- Don’t treat
_idorder as a strict event order, especially across multiple application servers. - If you need a reliable ordering, store an explicit sequence or timestamp field, or use a field that the server assigns.
The timestamp is the client’s clock
If a client has a wrong clock, its ObjectIds carry a wrong time. A phone, a batch script on a misconfigured host, or a test fixture can all produce IDs far in the past or future. Range queries on _id will place those documents accordingly.
It records creation of the ObjectId, not of the document
If application code builds an ObjectId ahead of time, or you import data and keep the original _id values, the embedded time reflects when the ID was generated or originally created. Documents created by insertMany from one process in a loop also share nearly identical timestamps, so don’t expect second-level distinctions within a batch.
Resolution is one second
You cannot distinguish events that happened within the same second using the timestamp portion alone.
Not every _id is an ObjectId
_id can be a string, a number, a UUID or a compound document. getTimestamp() exists only on ObjectId values, and a range query using ObjectId bounds will not match documents whose _id is of another BSON type, because MongoDB compares types in a defined order. If a collection mixes types, check with:
db.orders.aggregate([
{ $group: { _id: { $type: "$_id" }, n: { $sum: 1 } } }
])
Privacy and guessability
Because an ObjectId reveals when a record was created, exposing it in public URLs leaks that information. The random and counter parts are also not designed to be secret, so don’t use ObjectIds as access tokens or unguessable identifiers.
Quick reference
| Task | Expression |
|---|---|
| Read creation time | id.getTimestamp() |
| Read it in a pipeline | { $toDate: "$_id" } |
| ObjectId at a date | ObjectId(hexSeconds + "0000000000000000") |
| Documents since a date | find({ _id: { $gte: fromDate } }) |
| Newest first | find().sort({ _id: -1 }) |
Check _id types |
$group on { $type: "$_id" } |
When you check a recent-writes question from a phone, for example, “did anything get inserted in the last hour?”, an _id range filter is a compact query to type. A client such as Bussola accepts shell-syntax filters, but check that your client lets you write ObjectId values, since a plain string will not match an ObjectId field.
Summary checklist
- The first 4 bytes of an ObjectId are the creation time in seconds (UTC).
- Use
getTimestamp()or$toDateto read it. - Build bounds by padding an 8-hex-character timestamp with 16 zeros.
- Use half-open ranges:
$gtestart,$ltend. - Don’t rely on
_idorder for strict event sequencing across clients. - Store an explicit
createdAtif the clock source, sub-second precision or non-ObjectId_idtypes matter to you.
Bussola is a free MongoDB client for iPhone: query, edit and aggregate over a direct connection, with no backend.
Coming soon to the App Store