Stage 1 · Lesson 4 of 8
The _id field and ObjectId
Every document has an _id , its , which must be unique within the collection and cannot be changed. If you do not supply one, MongoDB generates an ObjectId: a 12-byte value made of a 4-byte timestamp in seconds, a 5-byte random value and a 3-byte counter.
That means ObjectIds are unique without asking the server, and they sort roughly by creation time, so sorting on _id gives you approximately newest last. You can read the creation time with ObjectId(...).getTimestamp(). You may use your own _id, such as a product code, if it is truly unique and never changes. The collection always has an on _id.
Common trapcomparing an ObjectId with its string form: { _id: "65f..." } matches nothing, because a string is not an ObjectId.
A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock
Resources for this stage
Start with
- CourseFreeMongoDB University
MongoDB
Free: start with the introduction to MongoDB and Atlas setup lessons, which use the same sample data
Practise
Keep handy
Also worth your time
A balanced comparison of where a document database fits and where a relational one wins