MongoDB

Stage 1 · Lesson 4 of 8

The _id field and ObjectId

Documents and your setup

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

  • CourseFree
    MongoDB University

    MongoDB

    Free: start with the introduction to MongoDB and Atlas setup lessons, which use the same sample data

Practise

  • Paste a few documents and a query and run it in the browser, no install needed

Keep handy

  • The mongosh docs: connecting, running scripts and the shell helpers such as show and use

  • The Compass docs for the Schema, Explain Plan and Aggregations tabs you will use later

Also worth your time

Mark this stage as not done?