In this lesson, you will learn how to structure document-based data by nesting related information directly within a single record, mirroring the way your application code organizes objects.
Moving Beyond Relational Tables
In a traditional relational model, if you had a User and their Addresses, you would be forced to create two separate tables and perform a JOIN to retrieve the data. In a document model, you can treat the address as an embedded object or a collection of addresses as a nested array. This keeps related data physically together, which is highly efficient for read-heavy workloads where the application needs the full "user profile" in one go.
Mapping to Application Objects
When you design your document, you should structure it to match the JSON-like objects your application expects. For instance, consider a user profile that contains a list of preferences and a nested shipping address:
{
"username": "jdoe",
"preferences": ["dark_mode", "email_notifications"],
"shipping_address": {
"street": "123 Tech Lane",
"city": "Silicon Valley",
"zip": "94025"
}
}
By nesting the shipping_address as an object, you ensure that the database returns the entire object in a single query. By using an array for preferences, you maintain a simple, flat list that is easy for your application to iterate through without needing separate "lookup" tables.
When to Nest
The key to handling nested structures is to nest only when the data is "owned" by the parent document. Ask yourself: Does this information make sense outside the context of the user? If the answer is no, nesting it inside the document makes your application logic significantly cleaner and faster. You avoid the complexity of relational joins while keeping the document intuitive and readable.
If you find your nested arrays growing unboundedly (e.g., millions of log entries under one user), you have pushed the "nesting" concept too far. In those cases, keep the primary user document lean and refer to external collections.
Key Takeaway: Design your document structures to encapsulate data that is logically coupled, allowing your database to serve complete application objects in a single read operation.