MongoDB Modeling and Indexes
Model documents around access patterns; embed bounded data read with a parent and reference independently growing or shared entities.
How to apply it
Indexes speed reads but consume storage and slow writes. Design compound indexes around equality filters, sort, and range predicates. Use explain execution statistics on representative data and inspect documents examined, keys examined, and sort stages.
Worked example
A project list may benefit from an index on organizationId, createdAt descending, and _id descending; benchmark if status should also be indexed.
Common mistakes to avoid
Indexing every field or assuming one index optimizes every query.
Practice task
Implement this concept in the capstone. Add one positive test, one negative or failure-path test, and a short note explaining the trade-off you chose.
projectSchema.index({ organizationId: 1, createdAt: -1, _id: -1 });
const projects = await Project.find({
organizationId: req.auth.organizationId,
status: 'active'
}).sort({ createdAt: -1, _id: -1 }).limit(25).lean();- Model documents around access patterns; embed bounded data read with a parent and reference independently growing or shared entities.
- Indexes speed reads but consume storage and slow writes.
What is the strongest production practice for MongoDB Modeling and Indexes?