This chapter follows Pagination in MongoDB. MongoDB geospatial queries operate on GeoJSON geometry stored in documents and indexed with 2dsphere (spherical) or legacy 2d (flat plane).
GeoJSON types and 2dsphere indexes
{ "name": "Central Park Cafe", "location": { "type": "Point", "coordinates": [-73.9654, 40.7829] }}db.places.createIndex({ location: '2dsphere' })Supported types include Point, LineString, Polygon, MultiPolygon, and others listed in the MongoDB GeoJSON docs.
$near and $geoWithin
Find places near a point (meters on a sphere):
db.places.find({ location: { $near: { $geometry: { type: 'Point', coordinates: [-73.98, 40.75] }, $maxDistance: 500, }, },})Find places inside a polygon:
db.places.find({ location: { $geoWithin: { $geometry: { type: 'Polygon', coordinates: [[ [-74.0, 40.7], [-73.9, 40.7], [-73.9, 40.8], [-74.0, 40.8], [-74.0, 40.7], ]], }, }, },})Circle on a sphere with $centerSphere (radius in radians):
db.places.find({ location: { $geoWithin: { $centerSphere: [[-73.98, 40.75], 0.01], }, },})$geoIntersects
Return documents whose geometry intersects a query geometry—useful for overlapping regions:
db.regions.find({ boundary: { $geoIntersects: { $geometry: { type: 'Point', coordinates: [-73.95, 40.76] }, }, },})$geoNear in aggregation
$geoNear must be the first stage. It outputs distance in meters when using 2dsphere:
db.places.aggregate([ { $geoNear: { near: { type: 'Point', coordinates: [-73.98, 40.75] }, distanceField: 'distanceMeters', maxDistance: 2000, spherical: true, }, }, { $limit: 10 },])Legacy 2d indexes
Flat 2d indexes suit legacy coordinate pairs [x, y] on a plane, not GeoJSON. New applications should prefer 2dsphere unless you have a flat map with non-geographic units.
Store locator example
import { Db, ObjectId } from 'mongodb';
interface Place { name: string; location: { type: 'Point'; coordinates: [number, number] };}
export async function nearStores(db: Db, lng: number, lat: number, maxMeters: number) { return db.collection<Place>('places').find({ location: { $near: { $geometry: { type: 'Point', coordinates: [lng, lat] }, $maxDistance: maxMeters, }, }, }).limit(20).toArray();}Ensure the compound filter fields you add (for example category: 'cafe') are compatible with the geospatial index or use a partial index.
Next: Replica sets in MongoDB.
Check your understanding
Question 1 of 5
0 of 5 checked