Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

MDB
MongoDB
0/10 completed
Beginner
What is MongoDB?Inserting and finding documentsUpdating and deleting
Intermediate
Query operatorsSorting, paging and projectionIndexes and explain()
Advanced
The aggregation pipelineJoins, facets and window functionsSchema design and validation
Pro
Drivers, transactions and scaling
Tracks / MongoDB / Advanced

Schema design and validation

"Schemaless" is a myth. MongoDB doesn't force a schema on you, which means you are responsible for designing one. The golden rule:

Data that is accessed together should be stored together.

In SQL you design around the data (normalise, then join). In MongoDB you design around how your app reads and writes it.

Embed or reference?

Embedding puts related data inside the document:

js
// A blog post with its comments embedded
{
  _id: 1,
  title: 'Learning MongoDB',
  author: { id: 7, name: 'Asha' },          // a snapshot of what the page displays
  tags: ['mongodb', 'databases'],
  comments: [
    { user: 'Rahul', text: 'Great post!', at: ISODate('2025-01-02') },
    { user: 'Priya', text: 'Thanks!', at: ISODate('2025-01-03') }
  ]
}

Referencing stores an id and keeps the related data in another collection, like a foreign key:

js
// orders reference customers
{ _id: 101, customerId: ObjectId('…'), total: 49 }
Embed when… Reference when…
You read them together (post + comments) You often read them separately
It's a "contains" relationship (an order has line items) Many documents share it (a product appears in many orders)
The embedded list is bounded (a few to a few hundred) The list can grow without limit (all the orders of a customer)
The data rarely changes on its own It changes often and independently

One read, one write, no joins: embedding is why well-designed MongoDB apps are fast. But a document can't exceed 16 MB, and huge arrays get slow to update, so unbounded arrays are the #1 anti-pattern.

Relationship patterns

One-to-few (a user's 2 addresses): embed.

One-to-many (a product's 500 reviews): reference from the "many" side (review.productId), maybe also embed the 3 latest reviews in the product for the product page. This is the subset pattern.

One-to-squillions (a server's log lines): always reference from the child, never an array in the parent.

Many-to-many (students and courses): arrays of ids on one or both sides, such as course.studentIds, if bounded, or a separate "enrollments" collection.

Duplicating data on purpose

Order documents in the shop store items: [{ product: 'Laptop', price: 899 }], a copy of the product name and price. That's intentional: an order must remember the price at the time of purchase, even if the product's price changes later. This is called the extended reference pattern. Copy fields that the reader needs and that rarely change, and accept that updates to them may need to touch several documents.

Other useful patterns

Pattern Idea Example
Computed Store pre-calculated values, update them on write product.reviewCount, product.avgRating updated with $inc
Bucket Group many small items into one document per time window IoT readings: one document per sensor per hour
Polymorphic Different shapes in one collection, with a type field { type: 'tv', screenSize: 55 } and { type: 'shirt', size: 'M' }
Schema versioning Add schemaVersion and migrate documents lazily Read old shapes, write the new one

Here's the computed pattern: keep a review count and rating sum up to date with one atomic update, so the product page never has to aggregate:

MongoDB shell (simulated) · editable

$slice: -3 keeps only the 3 most recent reviews in the array (the subset pattern), so it can never grow unbounded.

Schema validation

Flexibility is great until a bug writes price: "free". Schema validation makes the server reject bad documents. The standard way is a $jsonSchema validator:

MongoDB shell (simulated) · editable

Fields not listed in properties are still allowed, so you keep flexibility where you want it. Validators can also use query operators, and you can add one to an existing collection:

MongoDB shell (simulated) · editable

Set validationAction: 'warn' to log violations without rejecting them while you roll out a validator on messy existing data.

Schemas in application code

Most Node.js projects also define the schema in code, with Mongoose:

js
import mongoose from 'mongoose';

const productSchema = new mongoose.Schema({
  name:     { type: String, required: true, trim: true },
  price:    { type: Number, required: true, min: 0 },
  category: { type: String, enum: ['Electronics', 'Kitchen', 'Home'] },
  tags:     [String],
}, { timestamps: true });                 // adds createdAt and updatedAt

export const Product = mongoose.model('Product', productSchema);

await Product.create({ name: 'Mug', price: 8.99, category: 'Kitchen' });
const cheap = await Product.find({ price: { $lt: 10 } }).sort({ price: 1 });

Or with TypeScript types plus a validation library like Zod, and the official driver. Use both app-level validation (friendly error messages) and a server-side validator (a guarantee).

Practice

Design a schema for a recipe app, where users browse recipes (with ingredients and steps), leave ratings, and save favourites:

  1. Decide what to embed and what to reference, and why. (Ingredients? Ratings? Favourites?)
  2. Create a recipes collection with a $jsonSchema validator requiring a title, at least one ingredient, and minutes between 1 and 1440.
  3. Insert one valid and one invalid recipe.
MongoDB shell (simulated) · editable
✎ Check your understanding

1.What is the core principle of MongoDB schema design?

2.A customer may place thousands of orders over the years. Where do the orders go?

3.Why does each order store a copy of the product's price?

← Joins, facets and window functions