Create a 2d Index

To build a geospatial 2d index, use thedb.collection.createIndex() method and specify 2d. Use thefollowing syntax:

  1. db.<collection>.createIndex( { <location field> : "2d" ,
  2. <additional field> : <value> } ,
  3. { <index-specification options> } )

The 2d index uses the following optional index-specificationoptions:

  1. { min : <lower bound> , max : <upper bound> ,
  2. bits : <bit precision> }

Define Location Range for a 2d Index

By default, a 2d index assumes longitude and latitude and has boundariesof -180 inclusive and 180 non-inclusive. Ifdocuments contain coordinate data outside of the specified range,MongoDB returns an error.

Important

The default boundaries allow applications to insertdocuments with invalid latitudes greater than 90 or less than -90.The behavior of geospatial queries with such invalid points is notdefined.

On 2d indexes you can change the location range.

You can build a 2d geospatial index with a location range other thanthe default. Use the min and max options when creating theindex. Use the following syntax:

  1. db.collection.createIndex( { <location field> : "2d" } ,
  2. { min : <lower bound> , max : <upper bound> } )

Define Location Precision for a 2d Index

By default, a 2d index on legacy coordinate pairs uses 26 bits ofprecision, which is roughly equivalent to 2 feet or 60 centimeters ofprecision using the default range of -180 to 180. Precision is measuredby the size in bits of the geohash values used to store locationdata. You can configure geospatial indexes with up to 32 bits ofprecision.

Index precision does not affect query accuracy. The actual grid coordinatesare always used in the final query processing. Advantages to lowerprecision are a lower processing overhead for insert operations and useof less space. An advantage to higher precision is that queries scansmaller portions of the index to return results.

To configure a location precision other than the default, use thebits option when creating the index. Use following syntax:

  1. db.<collection>.createIndex( {<location field> : "<index type>"} ,
  2. { bits : <bit precision> } )

For information on the internals of geohash values, seeCalculation of Geohash Values for 2d Indexes.