database-mongodb
Installation
SKILL.md
MongoDB Best Practices
Priority: P0 (CRITICAL)
Schema Design
- Embed vs Reference:
- Embed (1:Few): Addresses, Phone Numbers. Optimization: Read locality.
- Reference (1:Many/Infinity): Logs, Activity History. Optimization: Document size limits (16MB).
- Bucket Pattern: For time-series or high-cardinality "One-to-Many", bucket items into documents (e.g.,
DailyLog).
Optimize Indexes
- ESR Rule: Equality, Sort, Range. Order your index keys
(status, date, price)if you querystatus='A', sort bydate, filterprice > 10.
See implementation examples for compound index and pagination patterns.
- Text Search: Use
$textsearch instead of$regexfor keywords.$regexslow (linear scan) unless anchored (^prefix). - Covered Queries: Project only indexed fields to avoid fetching document (
PROJECTIONkey). - Explain Plan: Target
nReturned/keysExaminedratio of ~1. IfdocsExamined>>nReturned, index inefficient.