All academies
Roadmap
LEVEL 1 · INTRODUCTION

ObjectId & BSON Types

10 min read

Every document has a unique _id field. If you don't provide one, MongoDB generates an ObjectId: a 12-byte value that encodes creation time, random machine/process bits, and a counter — so it is unique without any coordination between servers.

Anatomy of an ObjectId
ObjectId("64f1a2b3c4d5e6f7a8b9c0d1")
//        |--------|----------|------|
//        timestamp   random    counter
//        (4 bytes)  (5 bytes) (3 bytes)

BSON types you'll actually use

String, Number (int32, int64, double, decimal128), Boolean, Date, Array, Object (embedded document), ObjectId, Null, and Binary. BSON keeps type information, so "42" (string) and 42 (number) are different values — a common source of query bugs.

Embedding vs referencing

You can nest related data inside a document (embedding) or store an id pointing to a document in another collection (referencing). Rule of thumb: *data that is read together should be stored together* — embed by default, reference when data is shared, unbounded, or updated independently.

mongosh
// Embedding
{ name: "Aarav", address: { city: "Mumbai", zip: "400001" } }

// Referencing
{ name: "Aarav", addressId: ObjectId("...") }

Try it yourself

db.users.find({}, { name: 1, city: 1 })
Run in Shell

Check your understanding

Q1.

What is encoded in the first 4 bytes of an ObjectId?

Q2.

A collection contains { qty: "5" } (string). What does this query return?

code
db.items.find({ qty: 5 })
Q3.

Embedding related data is a good default when the data is always read together.