MongoDB โ Geospatial & TTL Indexes
Build location-aware apps with 2dsphere GeoJSON indexes and set auto-expiring document caches with TTL indexes.
1TTL (Time-To-Live) Auto-Expiring Documents
TTL Index Example
// Automatically delete session documents 3600 seconds (1 hour) after createdAt
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
);
2Geospatial 2dsphere Indexing
GeoJSON Location Query
// Store location as GeoJSON Point [longitude, latitude]
db.stores.insertOne({
name: "Central Store",
location: { type: "Point", coordinates: [78.4867, 17.3850] }
});
// Index location
db.stores.createIndex({ location: "2dsphere" });
// Find stores within 5000 meters
db.stores.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [78.48, 17.38] },
$maxDistance: 5000
}
}
});