Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Location Coordinates as a Shard key in MongoDB

Is it possible to have the lat and long coordinates as a shard key in a collection with a geo-spatial index in mongoDB? If not, can you suggest any efficient way to calculate a shard key on the applcation server, based on the location ?

like image 548
Manos Avatar asked Dec 27 '22 04:12

Manos


1 Answers

It is not possible to use a geospatial index as your shard key index.

See the "Important" note here: http://docs.mongodb.org/manual/core/2d/#d-indexes

Important; You cannot use a 2d index as a shard key when sharding a collection. However, you can create and maintain a geospatial index on a sharded collection by using a different field as the shard key.

You cannot use an array field as your shard key either. So the only way you can do it is if you store your location twice, once as 2d indexed geo-location array, and again as two regular fields that you can create a normal compound index on and then shard on that compound key.

However, since the shard key is immutable, make sure that your location field is final - i.e. that it is always known at creation time and it cannot be changed.

like image 97
Asya Kamsky Avatar answered Jan 13 '23 07:01

Asya Kamsky