Loading Depth Study
Preparing your workspace
An index is a data structure that helps MongoDB find matching documents more efficiently.
Without an appropriate index, MongoDB may need to examine many or all documents to answer a query. Indexes can significantly improve read performance, but they also consume storage and add overhead to writes because index entries must be maintained. Common indexes include single-field and compound indexes. Index design should follow real query patterns. MongoDB tools such as explain can help developers understand how a query is being executed.
If the application frequently searches courses by slug, an index on slug can make those lookups much more efficient.
const courses = db.collection("courses");
await courses.createIndex({ slug: 1 }, { unique: true });
await courses.createIndex({ categoryId: 1, published: 1 });
const course = await courses.findOne({
slug: "react-fundamentals"
});
console.log(course);The collection gets a unique slug index and a compound category/published index for common lookup patterns.