$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.

CategoryGeospatial
MongoDB Version2.4+
Example Languagemongosh (Shell)

📝 Syntax

{ <location field>: { $near: { $geometry: <Point>, $maxDistance: <meters> } } }

⚙️ Parameters

position fieldThe field storing the location.
Point geometryA GeoJSON Point with [longitude, latitude].
maxDistanceOptional; 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏