Geospatial Queries
2dsphere indexes, GeoJSON, $near, $geoWithin, and $geoIntersects
Skills taught: mongodb.geospatial
GeoJSON and Coordinate Storage
MongoDB uses the GeoJSON format for storing location data. GeoJSON is an open standard for encoding geographic data as JSON. For points, you store a type: 'Point' object with coordinates: [longitude, latitude].
Warning: GeoJSON uses [longitude, latitude] order — the OPPOSITE of what many people expect! Google Maps shows (latitude, longitude) but GeoJSON is [longitude, latitude]. Always double-check your coordinate order when inserting location data.
// Store a place with GeoJSON coordinates
await places.insertOne({
name: 'Taj Mahal',
category: 'monument',
// GeoJSON Point — [LONGITUDE, LATITUDE] order!
location: {
type: 'Point',
coordinates: [78.0421, 27.1751] // [lng, lat] — Agra, India
},
rating: 4.9
});
// Insert multiple places
await places.insertMany([
{ name: 'Red Fort', location: { type: 'Point', coordinates: [77.2410, 28.6562] } },
{ name: 'Gateway of India', location: { type: 'Point', coordinates: [72.8347, 18.9220] } },
{ name: 'Qutub Minar', location: { type: 'Point', coordinates: [77.1855, 28.5244] } }
]);
// Create the 2dsphere index (REQUIRED before geospatial queries)
await places.createIndex({ location: '2dsphere' });
$near — Find Nearby Documents
$near returns documents sorted by distance from a given point. You can specify a maximum distance ($maxDistance) and minimum distance ($minDistance) in meters.
// Find restaurants within 2km, sorted nearest first
const nearby = await restaurants.find({
location: {
$near: {
$geometry: {
type: 'Point',
coordinates: [77.2090, 28.6139] // [lng, lat] — New Delhi
},
$maxDistance: 2000, // 2000 metres = 2 km
$minDistance: 0 // optional minimum (omit for 0)
}
},
isOpen: true // combine with other filters
}).limit(10).toArray();
console.log(`Found ${nearby.length} open restaurants within 2km`);
nearby.forEach(r => console.log(r.name, r.cuisine));
// Get distance in the result using aggregation
const withDistance = await restaurants.aggregate([
{
$geoNear: {
near: { type: 'Point', coordinates: [77.2090, 28.6139] },
distanceField: 'distance', // adds 'distance' field (in metres)
maxDistance: 2000,
query: { isOpen: true },
spherical: true
}
},
{ $limit: 10 },
{ $project: { name: 1, cuisine: 1, distanceKm: { $divide: ['$distance', 1000] } } }
]).toArray();
Tip: Use $geoNear as the FIRST stage in an aggregation pipeline to get distances in the result documents. It adds a 'distanceField' to each result with the distance in meters, which you can then convert to km or miles.
$geoWithin — Points Inside a Shape
$geoWithin returns documents whose location falls within a given shape — a polygon, circle, or bounding box. Unlike $near, it does not sort by distance.
// Find all deliveries within a service area polygon
const serviceArea = [
[77.1500, 28.5900], // Southwest corner [lng, lat]
[77.2500, 28.5900], // Southeast corner
[77.2500, 28.7000], // Northeast corner
[77.1500, 28.7000], // Northwest corner
[77.1500, 28.5900] // Close the polygon (repeat first point)
];
const inZone = await deliveries.find({
dropLocation: {
$geoWithin: {
$geometry: {
type: 'Polygon',
coordinates: [serviceArea] // array of arrays — outer ring first
}
}
}
}).toArray();
// Simpler: $centerSphere — find within a radius (no polygon needed)
// $centerSphere uses radians, not meters!
const radiusInKm = 5;
const earthRadiusKm = 6378.1;
const inRadius = await places.find({
location: {
$geoWithin: {
$centerSphere: [
[77.2090, 28.6139], // [lng, lat] center
radiusInKm / earthRadiusKm // radius in radians!
]
}
}
}).toArray();
Storing Delivery Zones as Polygons
// Store a delivery zone as a GeoJSON Polygon
await zones.insertOne({
name: 'Zone A — North Delhi',
deliveryFee: 29,
boundary: {
type: 'Polygon',
coordinates: [[
[77.1500, 28.5900],
[77.2500, 28.5900],
[77.2500, 28.7000],
[77.1500, 28.7000],
[77.1500, 28.5900] // close the ring
]]
}
});
await zones.createIndex({ boundary: '2dsphere' });
// Check if a delivery address is within any zone
const customerLocation = [77.2090, 28.6139]; // [lng, lat]
const matchingZone = await zones.findOne({
boundary: {
$geoIntersects: {
$geometry: {
type: 'Point',
coordinates: customerLocation
}
}
}
});
if (matchingZone) {
console.log(`Delivery available! Zone: ${matchingZone.name}, Fee: ₹${matchingZone.deliveryFee}`);
} else {
console.log('Sorry, outside delivery area');
}
Frequently Asked Questions
What coordinate order does GeoJSON use?
GeoJSON uses [longitude, latitude] order — the opposite of what many people expect. Google Maps, OpenStreetMap, and most GPS devices show (latitude, longitude), but GeoJSON and MongoDB store [longitude, latitude]. This is the #1 geospatial bug in MongoDB applications.
What is the difference between $near and $geoWithin?
$near returns documents sorted by distance from a point, closest first. It requires a 2dsphere index. $geoWithin returns all documents whose location falls within a given shape (polygon, circle), without distance sorting. $geoWithin can work without a 2dsphere index but is much faster with one.
Can I store multiple location types (points AND polygons) in one collection?
Yes. A single 2dsphere index can index multiple GeoJSON types in the same collection. Some documents can have Point locations, others can have Polygon boundaries — the same index serves $near (for points) and $geoWithin/$geoIntersects (for shapes).