syv
syv

Reputation: 3608

Get closest data using centerSphere - MongoDB

I'm trying to get the closest data from the following data

> db.points.insert({name:"Skoda" , pos : { lon : 30, lat : 30 } }) 
> db.points.insert({name:"Honda" , pos : { lon : -10, lat : -20 } }) 
> db.points.insert({name:"Skode" , pos : { lon : 10, lat : -20 } }) 
> db.points.insert({name:"Skoda" , pos : { lon : 60, lat : -10 } }) 
> db.points.insert({name:"Honda" , pos : { lon : 410, lat : 20 } }) 

> db.points.ensureIndex({ loc : "2d" })

then I tried

> db.points.find({"loc" : {"$within" : {"$centerSphere" : [[0 , 0],5]}}})

this time I got different error

error: {
    "$err" : "Spherical MaxDistance > PI. Are you sure you are using radians?",
    "code" : 13461

then I tried

> db.points.find({"loc" : {"$within" : {"$centerSphere" : [[10 , 10],2]}}})
error: {
    "$err" : "Spherical distance would require wrapping, which isn't implemented yet",
    "code" : 13462

How to get this done ? I just want to get the closest data based on the given radious from GEO point.

Thanks

Upvotes: 1

Views: 1613

Answers (2)

Burak
Burak

Reputation: 5764

Hope this helps:

The radius of the Earth is approximately 3963.192 miles or 6378.137 kilometers.

For 1 mile:

db.places.find( { loc: { $centerSphere: [ [ -74, 40.74 ] ,
                                    1 / 3963.192 ] } } )

Upvotes: 0

Jenna
Jenna

Reputation: 2396

A few things to note. Firstly, you are storing your coordinates in a field called "pos" but you are doing a query (and have created an index) on a field called "loc."

The $centerSphere takes a set of coordinates and a value that is in radians. So $centerSphere: [[10, 10], 2] searches for items around [10, 10] in a circle that is 2 * (earth's radius) = 12,756 km. The $centerSphere operator is not designed to search for documents in this large of an area (and wrapping around the poles of the Earth is tricky). Try using a smaller value, such as .005.

Finally, it is probably a better idea to store coordinates as elements in an array since some drivers may not preserve the order of fields in a document (and swapping latitude and longitude results in drastically different geo locations).

Upvotes: 2

Related Questions