| name | MongoDB |
| slug | mongodb |
| version | 1.0.1 |
| description | Design MongoDB schemas with proper embedding, indexing, aggregation, and production-ready patterns. |
| metadata | {"clawdbot":{"emoji":"đ","requires":{"anyBins":["mongosh","mongo"]},"os":["linux","darwin","win32"]}} |
When to Use
User needs MongoDB expertise â from schema design to production optimization. Agent handles document modeling, indexing strategies, aggregation pipelines, consistency patterns, and scaling.
Quick Reference
| Topic | File |
|---|
| Schema design patterns | schema.md |
| Index strategies | indexes.md |
| Aggregation pipeline | aggregation.md |
| Production configuration | production.md |
Schema Design Philosophy
- Embed when data is queried together and doesn't grow unboundedly
- Reference when data is large, accessed independently, or many-to-many
- Denormalize for read performance, accept update complexityâno JOINs means duplicate data
- Design for your queries, not for normalized elegance
Document Size Traps
- 16MB max per documentâplan for this from day one; use GridFS for large files
- Arrays that grow infinitely = disasterâuse bucketing pattern instead
- BSON overhead: field names repeated per documentâshort names save space at scale
- Nested depth limit 100 levelsârarely hit but exists
Array Traps
- Arrays > 1000 elements hurt performanceâpagination inside documents is hard
$push without $slice = unbounded growth; use $push: {$each: [...], $slice: -100}
- Multikey indexes on arrays: index entry per elementâcan explode index size
- Can't have multikey index on more than one array field in compound index
$lookup Traps
$lookup performance degrades with collection sizeâno index on foreign collection (until 5.0)
- One
$lookup per pipeline stageânested lookups get complex and slow
$lookup with pipeline (5.0+) can filter before joiningâmassive improvement
- Consider: if you $lookup frequently, maybe embed instead
Index Strategy
- ESR rule: Equality fields first, Sort fields next, Range fields last
- MongoDB doesn't do efficient index intersectionâsingle compound index often better
- Only one text index per collectionâplan carefully; use Atlas Search for complex text
- TTL index for auto-expiration:
{createdAt: 1}, {expireAfterSeconds: 86400}
Consistency Traps
- Default read/write concern not fully consistentâ
{w: "majority", readConcern: "majority"} for strong
- Multi-document transactions since 4.0âbut add latency and lock overhead; design to minimize
- Single-document operations are atomicâexploit this by embedding related data
retryWrites: true in connection stringâhandles transient failures automatically
Read Preference Traps
- Stale reads on secondariesâreplication lag can be seconds
nearest for lowest latencyâbut may read stale data
- Write always goes to primaryâread preference doesn't affect writes
- Read your own writes: use
primary or session-based causal consistency
ObjectId Traps
- Contains timestamp:
ObjectId.getTimestamp()âextract creation time without extra field
- Roughly time-orderedâcan sort by
_id for creation order without createdAt
- Not randomâpredictable if you know creation time; don't rely on for security tokens
Performance Mindset
explain("executionStats") shows actual executionânot just theoretical plan
totalDocsExamined vs nReturned ratio should be ~1âotherwise index missing
COLLSCAN in explain = full collection scanâadd appropriate index
- Covered queries:
IXSCAN + totalDocsExamined: 0âall data from index
Aggregation Philosophy
- Pipeline stages are transformationsâthink of data flowing through
- Filter early (
$match), project early ($project)âreduce data volume ASAP
$match at start can use indexes; $match after $unwind cannot
- Test complex pipelines stage by stageâbuild incrementally
Common Mistakes
- Treating MongoDB as "schemaless"âstill need schema design; just enforced in app not DB
- Not adding indexesâscans entire collection; every query pattern needs index
- Giant documents via array pushesâhit 16MB limit or slow BSON parsing
- Ignoring write concernâdata may appear written but not persisted/replicated