Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 16

Document Database Architecture and Querying

This lesson is built with resources from youtube.com, medium.com and 1 more site.

Hello! Welcome to the third lesson in our module on Distributed Data Storage & Systems.

In our last lesson, we contrasted the ACID and BASE consistency models. We established that traditional relational databases typically follow the ACID model to guarantee correctness, while many NoSQL systems favor the BASE model for high availability and scalability, accepting eventual consistency.

Today, we delve into one of the most popular categories of NoSQL databases: document databases. Our goal is to describe the architecture and query patterns for document databases, using MongoDB as our primary example. As an architect, understanding this model is crucial because it offers immense flexibility and scalability for modern, data-intensive applications. We will explore how its architecture enables this flexibility and how its query patterns differ fundamentally from the relational world you're familiar with.

From Tables and Rows to Collections and Documents

The most significant shift from relational databases to document databases is the data model itself. Instead of storing data in tables with predefined columns and rows, document databases store data in flexible, self-describing structures called documents.

MongoDB vs. RDBMS Data Structure Correlation
This diagram shows the conceptual mapping between relational database concepts and MongoDB concepts. A 'Table' corresponds to a 'Collection,' a 'Row' corresponds to a 'Document,' and a 'Column' corresponds to a 'Field.'

These documents are typically in a JSON (JavaScript Object Notation) or BSON (Binary JSON) format. Think of a document as a self-contained object that holds all the information related to a single entity. For an enterprise architect, a useful analogy is to compare the rigid structure of a relational table to a strict SOAP API contract, whereas a document is like a flexible JSON payload in a RESTful API.

To see what this looks like in practice, let's look at a quick resource.

MongoDB: A Scientific Analysis of Its Modern Data Architecture

The following article, "MongoDB: A Scientific Analysis of Its Modern Data Architecture," starts with a great explanation of the document-centric data model.

Please read the first section, '1. Document-Centric Data Model'. Pay attention to the concept of BSON and how documents in the same collection can have different fields.

The key takeaway is flexibility. You can add new fields, nest objects, and include arrays within a document without having to alter a predefined schema for the entire collection. This "schema-on-read" approach greatly accelerates development, especially for applications where requirements evolve quickly.


The Art of Schema Design: Embedding vs. Referencing

In the relational world, you normalize data to reduce redundancy. In the document world, the primary goal is to design your schema based on your application's data access patterns. The central decision you'll make is whether to embed related data within a single document or to reference data in other documents.

This video provides an excellent and practical guide to this new way of thinking.

MongoDB Schema Design Best Practices

In "MongoDB Schema Design Best Practices," Joe Karlsson explains the fundamental shift in mindset from SQL to document databases. He focuses on the critical trade-off between embedding and referencing data.

Please watch from 02:45 to 22:34. The first part (until 12:04) contrasts the relational approach with the application-driven approach of MongoDB. The second part (from 12:04 onwards) dives deep into the pros and cons of embedding versus referencing. This is the most important concept in document database modeling.

To summarize the video's key points:

  • Embedding (like a JOIN done at write time):

    • Pros: All related data can be retrieved in a single read operation, which is extremely fast. Updates to the entire entity are atomic.
    • Cons: Can lead to large documents. MongoDB documents have a 16MB size limit, which acts as a guardrail against poor schema design. Duplication of data is possible if the same embedded object is needed elsewhere.
    • Use When: You have "contains" relationships (e.g., the comments for a specific blog post) and the related data is not excessively large and is always accessed with the parent document.
  • Referencing (like a JOIN done at read time):

    • Pros: Documents are smaller. Avoids data duplication. No risk of hitting the 16MB limit.
    • Cons: Requires a second query (an "application-level join") to fetch the related data, which adds latency.
    • Use When: The embedded data could be very large, or when the related data needs to be accessed on its own.

Modeling Relationships: From One-to-Few to One-to-Squillions

How you apply embedding or referencing depends on the cardinality of the relationship. A blog post by MongoDB provides a fantastic set of rules of thumb for this.

6 Rules of Thumb for MongoDB Schema Design

The article "6 Rules of Thumb for MongoDB Schema Design" breaks down how to handle different one-to-N relationships.

Please read the three sections under 'Basics': 'Modeling one-to-few,' 'One-to-many,' and 'One-to-squillions.' This provides concrete examples for applying the concepts from the video.

Here's a quick summary of the patterns:

Cardinality Relationship Example Recommended Pattern Implementation
One-to-Few A person has a few addresses Embedding Store the addresses in an array within the person document.
One-to-Many A product has hundreds of parts Referencing Store an array of part _ids within the product document.
One-to-Squillions A server generates millions of log entries Parent-Referencing Store the server _id in each individual log entry document.
Test your understanding!

You are designing the data model for a social media platform. A user can "like" many posts. How would you model the "likes" for a single user? Consider two scenarios:

  1. A user can like up to 1,000 posts.
  2. A user can potentially like millions of posts over their lifetime.

Justify your choice for each scenario.

Show answer
  1. Up to 1,000 Posts (One-to-Many): You would use the Referencing pattern. The user document would contain an array called liked_posts that stores the _ids of the posts they have liked. This is efficient because the array size is bounded and manageable. Embedding the full post documents would be wasteful.

  2. Millions of Posts (One-to-Squillions): You would use the Parent-Referencing pattern. The array of _ids in the user document could grow without bound, eventually hitting the 16MB document size limit and causing performance issues. The better approach is to create a separate likes collection. Each document in this collection would store the user_id and the post_id, effectively creating a link between the two. This schema can scale indefinitely.


MongoDB's Architecture: Storage and Scalability

Now that we understand how to model data, let's briefly look at the architecture that makes it all work.

The Storage Engine: WiredTiger

Modern MongoDB uses a storage engine called WiredTiger. Understanding its key features is important for an architect to reason about performance.

  • Document-Level Locking: Unlike older systems that might lock an entire table (or collection), WiredTiger uses fine-grained locking at the individual document level. This allows for high concurrency, as updates to different documents in the same collection do not block each other.
  • Compression: It automatically compresses data on disk, which reduces storage costs and often improves performance by reducing the amount of data that needs to be read from disk (I/O).
  • Indexes: It uses B-Tree indexes, similar to relational databases, to speed up queries. The internal mechanics have evolved to optimize lookups, especially for the primary _id field.

Horizontal Scalability: Sharding

To handle massive amounts of data and high traffic loads, MongoDB scales horizontally using a technique called sharding.

MongoDB Sharding Architecture
This diagram illustrates MongoDB's sharding architecture. Client applications connect to query routers (mongos), which direct operations to the correct shard based on a 'shard key'. Each shard is a replica set, providing high availability. Config servers store the metadata that maps data to shards.

In this architecture:

  1. Data is partitioned into chunks based on a shard key (a field you choose in your document).
  2. These chunks are distributed across multiple shards. Each shard is itself a replica set (a primary node with secondary copies) to ensure high availability.
  3. Query Routers (mongos) act as a smart proxy, receiving queries from your application and directing them to the appropriate shard(s) without the application needing to know where the data lives.

The choice of a shard key is one of the most critical architectural decisions when scaling MongoDB, as it determines how evenly data is distributed and how efficiently queries can be routed.


Querying: The Aggregation Framework

For simple queries (finding, inserting, updating documents), MongoDB's query language is straightforward. For more complex analytics—analogous to SQL's GROUP BY, joins, and subqueries—MongoDB provides the Aggregation Framework.

This framework processes documents through a multi-stage pipeline. Each stage transforms the documents and passes the results to the next stage. Common stages include:

  • $match: Filters documents (like a WHERE clause).
  • $group: Groups documents by a key and calculates aggregate values (like GROUP BY).
  • $lookup: Performs a left outer join to another collection (an application-level join executed on the server).
  • $project: Reshapes documents by adding, removing, or renaming fields (like SELECT).

This pipeline model is a powerful paradigm for performing complex data analysis directly within the database.


Conclusion

In this lesson, we've explored the architecture and query patterns of document databases through the lens of MongoDB.

Key Takeaways:

  • Document databases store data in flexible, self-describing BSON/JSON documents grouped into collections.
  • Schema design is driven by application query patterns, not strict normalization.
  • The fundamental modeling choice is embedding vs. referencing, which depends on the cardinality of the relationship (one-to-few, one-to-many, one-to-squillions).
  • MongoDB's WiredTiger storage engine provides performance features like document-level locking and compression.
  • MongoDB achieves horizontal scalability through sharding, distributing data across servers based on a shard key.
  • Complex queries and analytics are handled by the Aggregation Framework, which uses a multi-stage pipeline.

We've now seen how document databases offer a flexible and scalable alternative to relational databases. In our next lesson, we will explore another major type of NoSQL database as we describe the architecture and query patterns for column-family databases (e.g., Cassandra). We'll see how they are optimized for entirely different access patterns, particularly for write-heavy workloads at extreme scale.