$geoNear (Geo Near)
Last updated: 2026-10-09
$geoNear (Geo Near)
$geoNear outputs documents ordered by geographic proximity and must be the first pipeline stage, requiring a geospatial index on the collection. It supports a distanceField output, spherical or planar math, minDistance and maxDistance filters, and a key to choose among multiple geo fields. Each result gains a computed distance.
| Category | Advanced & Diagnostic |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $geoNear: { near: { type: "Point", coordinates: [ <longitude>, <latitude> ] }, distanceField: "<distanceField>", spherical: <bool>, maxDistance: <meters>, query: <filter> } }
⚙️ Parameters
| near | The reference point, a GeoJSON point or legacy coordinates array. |
|---|---|
| distanceField | Field name that receives the computed distance. |
| spherical | When true, computes distances using spherical geometry. |
| query | Additional query filter. |
Returns:Document stream ordered by distance, with the distanceField included
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $geoNear: places within 5 km
db.places.aggregate([
{ $geoNear: {
near: { type: 'Point', coordinates: [-73.98, 40.75] },
distanceField: 'dist',
spherical: true,
maxDistance: 5000
} }
])
Output:
// Sorted by distance ascending, each doc carries dist
📌 Notes
- Must be the first pipeline stage
- The collection needs a geospatial index (2dsphere or 2d)
- GeoJSON near requires spherical: true
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhat happens without a geospatial index?
AIt errors; the collection must have a 2dsphere or 2d geospatial index.
QCan results be filtered by distance?
AYes, via maxDistance and minDistance, in meters for spherical mode.
QCan additional query filters be added?
AYes, via the query parameter, e.g. { query: { category: 'restaurant' } }.