Typorithm · easy

Create Index

mongo-create-indexmongodbindexescompoundesr
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Create Index

0%

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.

01

{ field: 1 } ascending, { field: -1 } descending.

02

Compound key order follows ESR: equality, sort, range.

03

unique: true rejects duplicate values.

db.users.createIndex({ email: 1 }, { unique: true })
db.orders.createIndex({ customerId: 1, createdAt: -1 })
db.users.getIndexes()

Read the implementation

Connect each part of the code to the concept before you type.

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 })

2. Compound index

A compound index covers queries on customerId, then customerId+createdAt; the -1 sorts createdAt descending.

db.orders.createIndex({ customerId: 1, createdAt: -1 })

3. Field order matters

Order the keys by ESR: equality (customerId) first, then sort/range (createdAt).

{ customerId: 1, createdAt: -1 }

4. List indexes

getIndexes() returns every index on the collection, including the default _id index.

db.users.getIndexes()

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Create Index: Lesson & Practice · Typorithm | ApplyDjinn