Indexing
Text and TTL Indexes
Search-ish text matching, and documents that expire themselves.
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 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 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?
A text index supports $text search — tokenized, language-aware, not a replacement for equality or for a real search product. A TTL index deletes documents after expireAfterSeconds on a Date field; the cleaner runs periodically, not to the millisecond.