What are indexes
An index is an ordered lookup structure that lets MongoDB find documents without scanning the whole collection.
In this page:
What are indexes
Without an index a query performs a collection scan, reading every document. An index stores selected fields in a sorted B-tree with pointers to documents, so reads become fast, at the cost of extra storage and slower writes.
Every collection has a unique index on _id automatically.
Note:
Indexes speed up reads but slow down writes, so add only the ones you need.
Example: What are indexes
test> db.users.getIndexes()
[ { v: 2, key: { _id: 1 }, name: '_id_' } ]
test> db.users.createIndex({ email: 1 })
email_1
test> db.users.getIndexes().map(i => i.name)
[ '_id_', 'email_1' ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Indexing every field
- Never indexing query fields
- Forgetting _id is already indexed
Chapter Summary
- Indexes avoid full collection scans
- They are B-tree structures
- They cost storage and write speed
- _id is indexed automatically
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: