Skip to the workspace
Pebellslearn by building
Creating Indexes  ›  Capstone Project

Expiring (TTL) and Geospatial Indexes

Expiring 15 minA TTL index deletes documents automatically once a date field is older than a set number of seconds, and a 2dsphere index lets you find GeoJSON points near a location, with longitude written before latitude.

mongodb / Expiring (TTL) and Geospatial Indexes

Explore each scene at your own pace.

01 · The rule

The rule

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 expireAt field with expireAfterSeconds: 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.
  • $near returns results sorted nearest first and requires a geospatial index.
  • $maxDistance is in metres for GeoJSON points.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.