0

Following are my query,

db.places.save({"location":[ 12.948430, 77.573868 ]})
db.places.save({"location":[ 12.947813, 77.573653 ]})
db.places.ensureIndex( { "location" : "2d" } )
db.places.find({ "location" : { $within : { $center : [[12.948430, 77.573868],0.00015] } } })

In the query above how to select the units, is that meters or km? If i want to do meters currently i'm doing 0.00015 for radius of 15 meters, is this correct?

Siva
  • 3
  • 2

2 Answers2

0

You're using neither meters or kilometers. a 2d index means that you're saying your data is within a 2d coordinates system. .00015 in your case means .00015 degrees. In a flat 2d plane (or on a 2dsphere index with close enough coordinates for the error margin to not matter) you can follow this to convert to km.

I also recommend you index using the 2dsphere index rather than the 2d index if you're using actual coordinates that may be any reasonable distance from each other, since the curvature of the earth will screw up mongodb's calculations if it thinks the world is flat.

Community
  • 1
  • 1
jtmarmon
  • 5,727
  • 7
  • 28
  • 45
0

This is very interesting question! I've been struggling with this too! Lot's of googling, but the answer was just in MongoDB documentation.

From here you can learn that:

For spherical query operators to function properly, you must convert distances to radians, and convert from radians to the distances units used by your application.

To convert:

  • distance to radians: divide the distance by the radius of the sphere (e.g. the Earth) in the same units as the distance measurement.
  • radians to distance: multiply the radian measure by the radius of the sphere (e.g. the Earth) in the units system that you want to convert the distance to.

The radius of the Earth is approximately 3,959 miles or 6,371 kilometers.

How can we use it? Try this:

db.places.find( { location: { $geoWithin: { $centerSphere: [ [ 12.948430, 77.573868 ] ,
                                                           100 / 6371 ] } } } )

Please be advised, I used this technique and it worked for MongoDB 2.6.

Hope that helps!

Good luck!

Paweł Dawczak
  • 9,519
  • 2
  • 24
  • 37