Expiring (TTL) and Geospatial Indexes
Two new bookshop features: abandoned shopping carts should clean themselves up, and customers want to see the nearest store. Neither needs application code running on a timer or distance maths in your app. Each needs one special index.
The rule
TTL: a Date plus seconds means delete. 2dsphere: longitude first, then find near.
TTL (time to live) index: a single-field index on a Date field with expireAfterSeconds.
db.carts.createIndex({ updatedAt: 1 }, { expireAfterSeconds: 7200 }) // 2 hours
db.carts.insertOne({ user: "asha", items: [1, 4], updatedAt: new Date() })- A background task runs roughly every 60 seconds and deletes documents whose date is older than the limit, so removal is prompt but not exact to the second.
- The field must hold a BSON Date (or an array of Dates, where the earliest counts). A string or a missing field never expires.
- For a per-document deadline, index an
expireAtfield withexpireAfterSeconds: 0; each document then expires at its own time.
Geospatial (2dsphere) index: locations stored as GeoJSON points.
db.stores.insertOne({ name: "MG Road", location: { type: "Point", coordinates: [77.6070, 12.9750] } })
db.stores.createIndex({ location: "2dsphere" })
db.stores.find({ location: { $near: {
$geometry: { type: "Point", coordinates: [77.5946, 12.9716] },
$maxDistance: 3000 // metres
} } })- Coordinates are
[longitude, latitude], the reverse of how map apps display them. $nearreturns results sorted nearest first and requires a geospatial index.$maxDistanceis in metres for GeoJSON points.
The shortcut
Before creating either index, check the stored shape: a real Date for TTL, [longitude, latitude] for geo.
Cart document
updatedAt: new Date()is a Date. A TTL index will work.
Drills
Answer fast — trust the rule.
A TTL index has expireAfterSeconds: 3600. When is a document removed?
A cart has updatedAt: "2025-03-01T10:00:00Z" as a string. What happens with the TTL index?
In a GeoJSON point, which value comes first?
In what unit is $maxDistance when $near uses a GeoJSON point?
How are $near results ordered?
Remember
- TTL: a Date plus seconds means delete; 2dsphere: longitude first, then find near.
- Shortcut: check the stored shape, a real Date and
[longitude, latitude], before indexing. - Trap: string dates never expire, and swapped coordinates fail silently.
