What is the ObjectId in MongoDB?
Answer
An ObjectId is MongoDB's default primary key type — a 12-byte (24 hexadecimal characters) BSON value that is unique across all MongoDB instances worldwide. Structure of the 12 bytes: (1) 4 bytes — Unix timestamp (seconds since epoch) of when the ObjectId was created; (2) 5 bytes — random value unique to machine and process; (3) 3 bytes — auto-incrementing counter per process. Properties: Globally unique: virtually guaranteed uniqueness across all machines and processes; Sortable by creation time: since the timestamp is the most significant bytes, ObjectIds sort chronologically; Compact: 12 bytes vs 36-character UUID string; Creation timestamp extractable: ObjectId("507f1f77bcf86cd799439011").getTimestamp() returns the creation date. Creating ObjectIds: new ObjectId() — auto-generated; ObjectId("507f1f77bcf86cd799439011") — from string; ObjectId.createFromTime(timestamp) — for range queries. Range queries by time: since ObjectIds are sortable, you can find documents created in a time range without a separate timestamp field: db.orders.find({ _id: { $gte: ObjectId.createFromTime(startDate), $lt: ObjectId.createFromTime(endDate) } }). Custom _id: you can use any unique value as _id — string, integer, custom UUID — not required to use ObjectId.