Typorithm · medium

Special Indexes

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

Step 1 of 8 · intro card

Learn Special Indexes

0%

Indexes

Special indexes do more than lookups: { field: "text" } powers search, expireAfterSeconds auto-expires documents (TTL), and partialFilterExpression scopes a unique constraint.

A text index ({ body: "text" }) tokenizes the field so $text queries can search words and phrases.

A TTL index adds expireAfterSeconds to a date field, and MongoDB deletes each document that many seconds after its timestamp — ideal for sessions or logs.

A partial index with partialFilterExpression only indexes matching documents, which lets a unique constraint apply to just the rows you care about.

01

{ field: "text" } enables $text search.

02

expireAfterSeconds makes a TTL index that auto-deletes.

03

partialFilterExpression scopes which docs are indexed.

db.posts.createIndex({ body: "text" })
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
db.users.createIndex({ email: 1 }, { unique: true, partialFilterExpression: { email: { $exists: true } } })

Read the implementation

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

1. Text index

A "text" index tokenizes the field so $text searches can match words and phrases in body.

db.posts.createIndex({ body: "text" })

2. TTL expiry

expireAfterSeconds makes a TTL index that deletes documents 3600s after their createdAt date.

{ expireAfterSeconds: 3600 }

3. Partial filter

partialFilterExpression indexes only matching documents, so the unique rule applies only where email exists.

partialFilterExpression: { email: { $exists: true } }

4. Unique constraint

unique still enforces no duplicate emails, but here only across the partially indexed documents.

unique: true

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.

Special Indexes: Lesson & Practice · Typorithm | ApplyDjinn