Let me tell you a story about shopping that will help you understand a common architectural decision in building location-based platforms.
Imagine you're in a massive supermarket with 10,000 products across 50 aisles. You need to find specific items, but you also need to check if those items meet your requirements before buying them. How you approach this problem mirrors a fundamental decision software engineers face when building geospatial systems.
Scenario 1: Finding All Apples Within 5 Aisles
You're standing in Aisle 10 and want to see all the apples within 5 aisles from your current position. You have two options:
Option A: Ask the store employee (the database) to search all 50 aisles and bring you only the apples within 5 aisles.
Option B: Walk through all 50 aisles yourself, pick up every apple, and calculate which ones are within 5 aisles.
Obviously, Option A makes more sense. The store employee knows the layout, has the inventory system, and can efficiently find what you need.
Scenario 2: Checking if the Apple in Your Hand is Fresh
You're already holding an apple. You want to check if it's fresh enough to buy. Again, two options:
Option A: Walk back to the store employee and ask them to check the freshness of this specific apple you're holding.
Option B: Look at the apple in your hand and check it yourself right there.
Option B is clearly better. Why walk all the way back to ask about something you can check immediately?
These two scenarios perfectly illustrate when to use database aggregations versus application-level calculations in geospatial systems.
// "Hey database, search through 10,000 requests and find ones near me"
async function findNearbyRequests(
userLocation: Coordinates,
radiusMeters: number
) {
const pipeline = [
{
$geoNear: {
near: {
type: "Point",
coordinates: [userLocation.longitude, userLocation.latitude]
},
distanceField: "distance",
maxDistance: radiusMeters,
spherical: true
}
},
{ $limit: 50 }
];
return database.aggregate(pipeline);
}