Indexesmedium3-5 years

A session-token collection needs to expire tokens automatically after 30 minutes of inactivity, and a separate `orders` query needs a fast, small index for `status = "OPEN"` orders only, out of a collection that's 99% `CLOSED`. What index type solves each, and why wouldn't a plain index work as well for either?

A TTL index on a date field (lastActiveAt) expires a document N seconds after that field's value — the server runs a background task that deletes expired documents on its own, so the session collection self-cleans with no cron job or application-level cleanup code needed. A plain index on the same field would let a query filter or sort by it efficiently, but it does nothing to remove old documents; something would still have to run a deleteMany on a schedule. For the orders index, a partial index built with partialFilterExpression: { status: "OPEN" } only indexes the 1% of documents that are actually open, which makes it far smaller and cheaper to maintain than a plain index on status covering all the closed orders too — a plain index would faithfully index every CLOSED order as well, paying storage and write cost for values the query never asks for.

The lesson behind it →
More on Indexes