[MongoDB]: Geospatial Index

Let’s start with a simple example consisting of four points in a plane.
The meaning of the units of the coordinate systems can be whatever you choose: cms, miles, kilometers etc.

Now, let us insert these points into a collection named square:
To enable geospatial indexing, we set an appropriate index on the position array something below.

mongos> db.createCollection(“square”)
{ “ok” : 1 }
mongos>
mongos>
mongos> db.square.save( {_id: “A”, position: [0.001, -0.002]} )
mongos> db.square.save( {_id: “B”, position: [1.0, 1.0]} )
mongos> db.square.save( {_id: “C”, position: [0.5, 0.5]} )
mongos> db.square.save( {_id: “D”, position: [-0.5, -0.5]} )
mongos>
mongos>
mongos> db.square.ensureIndex( {position: “2d”} )
mongos>

Now we can perform queries like this using special MongoDB operators:

mongos> db.square.find( {position: { $near: [0,0], $maxDistance: 0.75 } } )
{ “_id” : “A”, “position” : [ 0.001, -0.002 ] }
{ “_id” : “C”, “position” : [ 0.5, 0.5 ] }
{ “_id” : “D”, “position” : [ -0.5, -0.5 ] }
mongos>
mongos>
mongos>
mongos> db.square.find( {position: { $near: [0,0], $maxDistance: 0.15 } } )
{ “_id” : “A”, “position” : [ 0.001, -0.002 ] }
mongos>
mongos>
mongos>
mongos> db.square.find( {position: { $within: { $box: [ [0.25, 0.25], [1.0,1.0] ] } } } )
{ “_id” : “C”, “position” : [ 0.5, 0.5 ] }
{ “_id” : “B”, “position” : [ 1, 1 ] }
mongos>
mongos>

  • Ask Question