MongoDB: Not getting correct result using $geoWithin operator

心已入冬 提交于 2019-11-28 11:51:37

I think your problem is, you are searching in a far too wide radius. According to the MongoDB documentation, the correct syntax of $centerSphere is:

db.<name>.find( {
    loc: { $geoWithin: 
     { 
        $centerSphere: [ [ <longitude>, <latitude> ],
        <radius in MILES>/3963.2 ] } 
     }
} )

You are now searching points in a 29153.88048637637 mile radius around your point, and both points are in that radius around the center you defined.

I hope this helps you :)

If you want to query related to $geoWithin or $centerSphere in future in your project then specify your field structure like this only:-

"location" : {
        "lng" : 77.15319738236303,
        "lat" : 28.434568229025803
    },
"redius" : 120

and then do query like:-

db.collection.find( {location: { $geoWithin: { $centerSphere: [ [ lat, lng ], radius/3963.2] } }} )
WhtPwny

Only because I have run into this a few times now, I'd like to elaborate on Ashutosh's answer.

The radius must be in radians, and the conversion is based on the sphere's radius in the units you wish to work with. Assuming you are working with Earth as your sphere and you want your $geoWithin to be in meters, then you'd set the radius field to meters/(6371*1000), or the distance you want divided by the radius of the earth in the units your distance represents.

This list should help:

  • Meters: distance in meters/6371000 (earth's mean radius in meters)
  • Kilometers: distance in km/6371
  • Miles: distance in miles/3959
  • Feet: distance in feet/20903520
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!