Course contentsShow
← Computer Science
Lesson 1720 of 2,87239. NoSQL and Modern DatabasesFree lesson

Document Structure and Nesting

Designing nested documents with embedded objects and arrays to model relationships within a single document.

Document Structure and Nesting

What You'll Learn

You'll learn how to design nested documents using embedded objects and arrays to model relationships within a single document in NoSQL document databases.

The Core Idea

In document databases (which use JSON or BSON formats), you can model relationships by embedding related data directly inside a document, rather than splitting it across multiple tables like in SQL databases. This means nesting objects within objects, or creating arrays of objects, all contained in one document.

Think of it like organizing information in a filing cabinet: instead of having separate folders that reference each other (like SQL foreign keys), you put all related papers into a single, comprehensive folder with labeled sections and subsections.

When to Nest

Embed documents when:

  • Data is always accessed together (a user and their profile settings)
  • There's a clear one-to-many relationship (a blog post and its comments)
  • The nested data has a limited, predictable size

Example structure:

{
  "user_id": 12345,
  "name": "Alice",
  "email": "alice@example.com",
  "addresses": [
    {
      "type": "home",
      "street": "123 Main St",
      "city": "Springfield"
    },
    {
      "type": "work",
      "street": "456 Office Blvd",
      "city": "Metropolis"
    }
  ],
  "preferences": {
    "theme": "dark",
    "notifications": true
  }
}

Here, addresses is an array of embedded objects, and preferences is a nested object. All data lives in one document, retrieved in a single operation—no joins needed.

Trade-offs

Nesting improves read performance but can complicate updates if nested data grows unbounded or needs independent querying.

Key Takeaway: Document nesting lets you embed related data as objects and arrays within a single document, optimizing for access patterns where information is retrieved together, eliminating the need for joins at query time.