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.
Make queries fast.
✍️ 2 exercises in this lessonWithout an index MongoDB scans every document. An index lets it find matches quickly.
db.students.createIndex({ city: 1 })createIndex({ email: 1 }, { unique: true })getIndexes() lists them; .explain() shows how a query runs.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.
db.students.createIndex({ city: 1 })
db.students.createIndex({ email: 1 }, { unique: true })
db.students.getIndexes()
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 } ]
Check what you learned in “MongoDB Indexes”.
Create an index on the email field.
db.users.({ email: 1 })
What is the downside of too many indexes?
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