ObjectId
ObjectId is the default 12-byte unique _id that MongoDB creates for each document.
In this page:
Syntax
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
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
- Comparing ObjectIds as strings
- Assuming ObjectIds are sequential integers
- 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: