Do mongodb’s 2dsphere index works on multidimensional coordinantes array?

Posted on

Question :

if i create a index like that :

db.createCollection("users")
db.users.ensureIndex({coordinates:"2dsphere"});

and then insert a point

var point = {
   type: "point",
   coordinates: [ 1, 2, 3, 4 ]
}

db.users.insert(point)

and after execute the query :

db.users.find(
  {
     coordinates:
       { $near :
          {
            $geometry: { type: "Point",  coordinates: [1, 2, 3, 3 ] },

            $maxDistance: 5000
          }
       }
   }
)

it seems to work, does de the 2dsphere index works as expected with multidimensional coordinates ?.

Answer :

The GeoJSON spec doesn’t support multidimensional coordinate positions in the format you are suggesting:

A position is represented by an array of numbers. There must be at least two elements, and may be more. The order of elements must follow x, y, z order (easting, northing, altitude for coordinates in a projected coordinate reference system, or longitude, latitude, altitude for coordinates in a geographic coordinate reference system). Any number of additional elements are allowed — interpretation and meaning of additional elements is beyond the scope of this specification.

A 2dsphere index in MongoDB 3.0+ will allow additional values in the coordinate array but only the first two values will be indexed and used in a 2dsphere query. This allows GeoJSON objects with additional elements (eg. altitude) to be saved in MongoDB, but interpretation or use of those extra values is up to your application code.

The MongoDB manual has information on supported GeoJSON objects.

There’s also a relevant feature suggestion you can upvote/watch in the MongoDB issue tracker: SERVER-691: n-dimensional geospatial search.

Leave a Reply

Your email address will not be published.