$nearSphere (Near, Spherical)

Last updated: 2026-10-09

$nearSphere (Near, Spherical)

$nearSphere returns geospatial documents ordered by spherical (great-circle) distance. `{ loc: { $nearSphere: { $geometry: { type: 'Point', coordinates: [lng, lat] }, $maxDistance: 5000 } } }`. Unlike $near, it always computes spherical distance in meters (planar distance is only used by $near on a 2d index). Requires a 2dsphere index.

CategoryGeospatial
MongoDB Version2.4+
Example Languagemongosh (Shell)

📝 Syntax

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

⚙️ Parameters

position fieldThe field storing the location.
Point geometryA GeoJSON Point with [longitude, latitude].
maxDistanceOptional; maximum spherical distance in meters.

Returns:Cursor of matching documents (ascending by spherical distance)

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $nearSphere: stores within 5 km (spherical)
// Coordinates are [longitude, latitude]
db.stores.find({
  loc: { $nearSphere: {
    $geometry: { type: 'Point', coordinates: [-73.97, 40.75] },
    $maxDistance: 5000
  } }
})

Output:

// Returns stores within 5 km, ordered by spherical distance

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QWhat is the difference between $nearSphere and $near?
A$nearSphere always uses spherical distance in meters; $near uses planar distance on a 2d index.
QWhat is the coordinate order?
AGeoJSON is [longitude, latitude]; reversing them lands far off.
QCan I use $near and $nearSphere together?
ANo, only one of them may appear in a query.
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%

🙏 帮我们做得更好

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

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