← Back to MongoDB Course | Chapter 8: Indexes | Lesson 1 of 7

What are indexes

An index is an ordered lookup structure that lets MongoDB find documents without scanning the whole collection.

In this page:

  1. What are indexes

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

bash
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
  1. Indexing every field
  2. Never indexing query fields
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.