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.