1. Single-field index
createIndex({ email: 1 }) builds an ascending index on one field; unique enforces no duplicate emails.
db.users.createIndex({ email: 1 }, { unique: true })Typorithm · easy
Step 1 of 8 · intro card
Indexes
createIndex builds single-field or compound indexes; order compound keys by ESR — equality, then sort, then range — and unique blocks duplicates.
A single-field index like { email: 1 } speeds lookups on one field; the unique option also rejects duplicate values.
A compound index like { customerId: 1, createdAt: -1 } serves queries that filter on customerId and sort by createdAt in one structure.
Field order is the whole game: follow ESR — put equality fields first, then the sort field, then range fields — and use getIndexes() to confirm what exists.
{ field: 1 } ascending, { field: -1 } descending.
Compound key order follows ESR: equality, sort, range.
unique: true rejects duplicate values.
db.users.createIndex({ email: 1 }, { unique: true })
db.orders.createIndex({ customerId: 1, createdAt: -1 })
db.users.getIndexes()Connect each part of the code to the concept before you type.
createIndex({ email: 1 }) builds an ascending index on one field; unique enforces no duplicate emails.
db.users.createIndex({ email: 1 }, { unique: true })A compound index covers queries on customerId, then customerId+createdAt; the -1 sorts createdAt descending.
db.orders.createIndex({ customerId: 1, createdAt: -1 })Order the keys by ESR: equality (customerId) first, then sort/range (createdAt).
{ customerId: 1, createdAt: -1 }getIndexes() returns every index on the collection, including the default _id index.
db.users.getIndexes()Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.