$near (Near, Distance Sorted)
Last updated: 2026-10-09
$near (Near, Distance Sorted)
$near returns geospatial documents ordered by distance from a point, ascending. `{ loc: { $near: { $geometry: { type: 'Point', coordinates: [lng, lat] }, $maxDistance: 1000 } } }`. Requires a 2dsphere or 2d index and cannot be combined with another $near or $nearSphere in the same query.
| Category | Geospatial |
|---|---|
| MongoDB Version | 2.4+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ <location field>: { $near: { $geometry: <Point>, $maxDistance: <meters> } } }
⚙️ Parameters
| position field | The field storing the location. |
|---|---|
| Point geometry | A GeoJSON Point with [longitude, latitude]. |
| maxDistance | Optional; maximum distance in meters. |
Returns:Cursor of matching documents (ascending by distance)
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $near: stores within 1000 m of the point
db.stores.find({
loc: { $near: {
$geometry: { type: 'Point', coordinates: [-73.97, 40.75] },
$maxDistance: 1000
} }
})
Output:
// Returns stores within 1000 m, ordered by distance ascending
📌 Notes
- Results are automatically sorted by distance; no sort needed
- Requires a 2dsphere (GeoJSON) or 2d (coordinate pairs) index
- $maxDistance is measured in meters (GeoJSON)
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QIs the $near result pre-sorted?
AYes, ascending by distance — no extra sort needed.
QIs an index mandatory for $near?
AYes, a 2dsphere or 2d index, otherwise it errors.
QWhen should I choose $near over $geoWithin?
APick $near for distance sorting; $geoWithin for containment only.