MongoDB Tutorial 0/120 lessons ~6 min read Lesson 18
Nested Documents
MongoDB lets you nest documents inside documents to any reasonable depth.
Course progress0%
Focus
6 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
MongoDB lets you nest documents inside documents to any reasonable depth. This is one of its superpowers: an order with line items, a user with an address, a post with comments — all fit in a single document, queryable in one round-trip.
Understanding the topic
When to nest (embed):
- The nested data is owned by the parent (a profile's address).
- You always read them together.
- They don't grow unbounded (cap at ~hundreds of sub-docs).
- You don't need to query them independently across many parents.
Syntax reference
js
db.users.insertOne({name: "Ada",address: { street: "1 King's Way", city: "London", zip: "EC1A" }});// Query nested with dot notationdb.users.find({ "address.city": "London" });
Real-world use
User profile + address + preferences = one document. UI loads in one query, no joins.
Best practices
- Embed 1:1 and 1:few; reference 1:many.
- Index nested fields you query (
address.city).
Common mistakes
- Embedding unbounded arrays (e.g. all of a user's posts) — eventually hits 16 MB.
Ready to mark this lesson complete?Track your journey across the entire course.