Skip to the workspace
Pebellslearn by building
Data Model & Data Types  ›  Lesson

ObjectId, Date and Timestamp

Object ID 12 minAn ObjectId is a 12-byte unique id that begins with its creation time, a Date is milliseconds since 1970 in UTC for application times, and Timestamp is an internal type MongoDB uses for replication.

mongodb / ObjectId, Date and Timestamp

Explore each scene at your own pace.

01 · The rule

The rule

ObjectId, Date and Timestamp

Every document you insert without an _id gets an ObjectId, and every "when did this happen?" question needs a Date. They look alike in the shell, both mention time, and a third type called Timestamp muddies it further. One rule sorts them out.

The rule

ObjectId identifies, Date records when, Timestamp is MongoDB's own business.

ObjectId is a 12-byte value, shown as 24 hexadecimal characters:

ObjectId("6650a1f2c3b4d5e6f7a8b9c0")
  • The first 4 bytes are a timestamp in seconds, so ObjectId(...).getTimestamp() returns when it was generated.
  • The next 5 bytes are random per process, and the last 3 bytes are a counter.
  • It is unique in practice without asking the server, which is why drivers can create it themselves. Sorting by _id gives roughly creation order, but only to the second.

Date is a signed 64-bit count of milliseconds since 1 January 1970, UTC. Use it for every application time: order placed, user joined, book released.

db.orders.insertOne({ bookId: 3, qty: 1, placedAt: new Date() })
db.orders.find({ placedAt: { $gte: ISODate("2025-01-01") } })

mongosh shows Dates as ISODate("..."), always in UTC. Convert to local time in your app, not in the database.

Timestamp is a separate BSON type: 32 bits of seconds plus a 32-bit counter. MongoDB uses it internally, for example in the replication log. The official advice is not to use it in your own documents; use Date.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.