Skip to content

Indexing

Text and TTL Indexes

Search-ish text matching, and documents that expire themselves.

IntermediateAbout 5 minutes

Two special indexes. Text is token search, not Google. TTL deletes documents after a delay. Neither replaces a normal B-tree for city or userId.

db.products.createIndex({ name: "text", tags: "text" })
db.products.find({ $text: { $search: "keyboard" } })
$text requires a text index. One text index per collection.

$text is language-aware stemming, not substring ($regex). You get a relevance score; you do not get typo-tolerance or facets. Atlas Search (or an external engine) is what you reach for when $text is not enough. Do not build { name: "text" } for find({ name: "Mechanical Keyboard" }) — that is an equality index.

db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 86400 })

// expire at a stored instant
db.sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })
TTL — field must be a date. Monitor runs about once a minute.

TTL does not fire at the exact second. Do not use it as a clock for 'unlock this seat now'. It deletes the document — not a field. Compound TTL indexes have extra rules; the date field is the expiry. A string that looks like a date is not a date.

Interview question

What are text indexes and TTL indexes for?

Think about it first.