Intermediate LevelMongoDB & Mongoose
How do 2dsphere Geospatial Indexes and $near spherical queries work?
❓ Interview Prompt: Explain 2dsphere indexes, GeoJSON objects (Point, Polygon), spherical geometry, $near, $geoWithin, and distance calculations.
MongoDB supports geospatial queries on a spherical Earth model using 2dsphere Indexes and standard GeoJSON data objects:
GeoJSON Point Structure:
'{ type: "Point", coordinates: [ longitude, latitude ] }' (Note: Longitude FIRST!).
Operators:
•
'$near': Finds points sorted by distance from target coordinates.
•
'$geoWithin': Finds points located inside a target polygon boundary.
Code Implementation Example
typescript
import { Schema, model } from 'mongoose';
const storeSchema = new Schema({
name: String,
location: {
type: { type: String, enum: ['Point'], default: 'Point' },
coordinates: [Number] // [longitude, latitude]
}
});
storeSchema.index({ location: '2dsphere' });
const StoreModel = model('Store', storeSchema);
// Find stores within 5000 meters (5km) of NYC coordinates
async function findNearbyStores(lng: number, lat: number) {
return await StoreModel.find({
location: {
$near: {
$geometry: { type: 'Point', coordinates: [lng, lat] },
$maxDistance: 5000
}
}
});
}💡Executing $near geospatial queries against a 2dsphere index.
🎯 Interview Key Takeaway
Remember that GeoJSON coordinates require Longitude FIRST, followed by Latitude ([lng, lat]).
#2dsphere#Geospatial#GeoJSON#$near#Intermediate
Back to all MongoDB & Mongoose Questions→