Working with Data Modeling
1. Understanding Document Model
| Principle | Detail |
|---|---|
| Schema-flexible | No fixed schema; validators optional |
| Aggregate-oriented | Design around access patterns |
| Joins minimized | Embed related data when read together |
| 16MB cap | Per document; design with this in mind |
2. Modeling One-to-One Relationships
| Approach | When |
|---|---|
| Embed | Always accessed together |
| Reference | Large, optional, or rarely needed |
// Embedded
{ _id: 1, name: "Alice", profile: { bio: "...", avatar: "..." } }
3. Modeling One-to-Many Relationships (embedded)
| Approach | When |
|---|---|
| Embed array | Bounded (< few hundred), fetched with parent |
| Subset pattern | Embed top N; full set referenced |
4. Modeling One-to-Many Relationships
| Approach | When |
|---|---|
| Child stores parent ref | Unbounded / large many-side |
| Parent stores ref array | Bounded many; common query lists ids |
5. Modeling Many-to-Many Relationships
| Approach | Trade-off |
|---|---|
| Two-way refs | Read flexibility; write to two places |
| Join collection | Like SQL; use $lookup |
| Embed on dominant side | Read pattern dictates |
6. Using Embedded Documents
| Pros | Cons |
|---|---|
| Single read | Doc size grows |
| Atomic updates | Cannot independently shard |
| No joins | Duplication if shared |
7. Using References with $lookup
| Aspect | Detail |
|---|---|
| Form | {$lookup: {from, localField, foreignField, as}} |
| Index foreignField | Critical for performance |
| Sharded | Supported on sharded foreign in 5.1+ |
8. Choosing Embedding vs Referencing
| Question | Embed | Reference |
|---|---|---|
| Always fetched together? | Yes | No |
| Bounded size? | Yes | Unbounded |
| Atomic updates needed? | Yes | No |
| Shared across parents? | No | Yes |
| High write contention? | No | Yes |
9. Handling Large Documents
| Strategy | Detail |
|---|---|
| Bucket pattern | Group time-series readings |
| Subset pattern | Embed hot subset; reference rest |
| GridFS | For files > 16MB |
| External storage | S3 / blob storage + reference URL |
10. Understanding Schema Flexibility
| Aspect | Detail |
|---|---|
| Add field | No migration; backfill optional |
| Remove field | $unset over time |
| Schema version | Add schemaVersion field |
| Validation | JSON Schema validator for guardrails |