Document database foundations

Understand the document model

See how MongoDB stores BSON documents in collections and how that model differs from rows in related SQL tables.

9 minute lesson

~~~

MongoDB stores documents inside collections. A document looks like a JavaScript object:

{
  name: 'Roger',
  age: 8,
  favoriteFoods: ['biscuits', 'carrots']
}

That similarity is why MongoDB feels approachable if you already write JavaScript. But MongoDB does not store JSON text. It stores BSON, a binary format that adds types JSON lacks: dates, 128-bit decimals, binary data, and object IDs. When you insert a document, MongoDB generates a unique _id of type ObjectId unless you provide one.

Documents can contain nested objects and arrays. In a relational database, a dog with three favorite foods needs a dogs table, a foods table, and a join between them. In MongoDB the whole thing can live in one document, and one read returns it complete.

Flexible schema, not no schema

Documents in the same collection do not need identical fields. One dog can have a microchipId, the next can skip it. This is often called schemaless, but flexible schema is more accurate: the structure lives in your application code, and you can enforce parts of it in the database later with schema validation.

Flexibility is a tool, not an excuse. If every document in a collection has a different shape, every reader must handle every shape. Aim for one intentional structure per collection, with deliberate variations.

The design consequence

The relational instinct is to normalize everything into separate tables and join at read time. Carrying that instinct into MongoDB produces the worst of both worlds: many tiny collections and no joins to connect them cheaply.

Instead, document boundaries follow how the application reads and writes data. Data you always load together belongs together. Try it on paper: take a small SQL schema you know, pick its most common query, and draw one document that answers that query in a single read. Do not assume every table must become a collection — that assumption is the most common modeling mistake people bring from SQL.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →