MongoDB Indexes

Make queries fast.

✍️ 2 exercises in this lesson

Without an index MongoDB scans every document. An index lets it find matches quickly.

  • db.students.createIndex({ city: 1 })
  • Unique: createIndex({ email: 1 }, { unique: true })
  • getIndexes() lists them; .explain() shows how a query runs.

Key Takeaways: MongoDB Indexes

Mastering MongoDB Indexes helps you write clean and reliable MongoDB code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

MongoDB Indexes Code Example

MongoDB
db.students.createIndex({ city: 1 })
db.students.createIndex({ email: 1 }, { unique: true })
db.students.getIndexes()
Output
city_1
email_1
[ { v: 2, key: { _id: 1 }, name: '_id_' }, { v: 2, key: { city: 1 }, name: 'city_1' }, { v: 2, key: { email: 1 }, name: 'email_1', unique: true } ]
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

MongoDB Indexes Practice Exercises

Check what you learned in “MongoDB Indexes”.

/ 2 solved
Fill in the blank

Create an index on the email field.

db.users.({ email: 1 })
✓ Correct! Not quite. Try again.
Multiple choice

What is the downside of too many indexes?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services