← Back to MongoDB Course | Chapter 2: CRUD — Create | Lesson 4 of 7

ObjectId

ObjectId is the default 12-byte unique _id that MongoDB creates for each document.

In this page:

  1. ObjectId
Syntax
javascript
ObjectId()
ObjectId("hex_string")
document._id.getTimestamp()

ObjectId

An ObjectId combines a 4-byte timestamp, a 5-byte random value and a 3-byte counter, so ids are unique across machines and roughly sortable by creation time. getTimestamp() extracts the creation time. The _id field is indexed automatically.

Note: ObjectIds are not secrets; do not use them as security tokens.

Example: ObjectId

bash
test> const id = new ObjectId()
test> id
ObjectId('65a1b2c3d4e5f60718293a4d')
test> id.getTimestamp()
ISODate('2024-01-12T14:30:11.000Z')
test> typeof id.toString()
string
test> ObjectId.isValid("65a1b2c3d4e5f60718293a4d")
true

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Comparing ObjectIds as strings
  2. Assuming ObjectIds are sequential integers
  3. Using them as unguessable tokens
Chapter Summary
  • ObjectId is a 12-byte unique id
  • Contains a timestamp
  • getTimestamp() reads the time
  • _id is indexed automatically
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.