MongoDB: Not getting correct result using $geoWith

2019-01-12 05:40发布

问题:

I am using $geoWithin for circle, and i am not getting expected result. There are two collections,one for users and second for items. I am setting radius and coordinates for item. so i have to find a users within that coordinates and radius.

User collection

{
    "_id" : NumberLong(25287),
    "_class" : "com.samepinch.domain.user.User",
    "name":"XYZ",
    "location" : [
        74.866247,
        31.63336
    ]
}

Item collection

{
    "_id" : NumberLong(46603),
    "itemName" : "Chandigarh",
    "categoryName" : "TRAVELLING",
    "location" : {
        "_id" : null,
        "longitude" : 77.15319738236303,
        "latitude" : 28.434568229025803,
        "radius" : 29153.88048637637
    }
}

as according to item coordinates and user coordinates,there is approx 500 km distance between two places.

Query

db.users.find({ location: { $geoWithin: { $center: [ [77.15319738236303,28.434568229025803], 29153.88048637637/3963.2] } } } ).count()

According to $geoWithin,user should not show,but it is showing. If i am doing something wrong,please help me.

Thanks

回答1:

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 :)



回答2:

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] } }} )



回答3:

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