Create a 2d Index创建2d索引

On this page本页内容

To build a geospatial 2d index, use the db.collection.createIndex() method and specify 2d. 要构建地理空间2d索引,请使用db.collection.createIndex()方法并指定2dUse the following syntax:使用以下语法:

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

The 2d index uses the following optional index-specification options:2d索引使用以下可选索引规范选项:

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

Define Location Range for a 2d Index定义2d索引的位置范围

By default, a 2d index assumes longitude and latitude and has boundaries of -180 inclusive and 180 non-inclusive. 默认情况下,2d索引假定经度和纬度,边界为-180(含)和180(不含)。If documents contain coordinate data outside of the specified range, MongoDB returns an error.如果文档包含超出指定范围的坐标数据,MongoDB将返回错误。

Important重要

The default boundaries allow applications to insert documents with invalid latitudes greater than 90 or less than -90. 默认边界允许应用程序插入无效纬度大于90或小于-90的文档。The behavior of geospatial queries with such invalid points is not defined.未定义具有此类无效点的地理空间查询的行为。

On 2d indexes you can change the location range.2d索引上,您可以更改位置范围。

You can build a 2d geospatial index with a location range other than the default. 可以使用非默认位置范围构建2d地理空间索引。Use the min and max options when creating the index. 创建索引时使用minmax选项。Use the following syntax:使用以下语法:

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

Define Location Precision for a 2d Index定义2d索引的位置精度

By default, a 2d index on legacy coordinate pairs uses 26 bits of precision, which is roughly equivalent to 2 feet or 60 centimeters of precision using the default range of -180 to 180. 默认情况下,传统坐标对上的2d索引使用26位精度,使用默认范围-180到180,大约相当于2英尺或60厘米的精度。Precision is measured by the size in bits of the geohash values used to store location data. 精度由用于存储位置数据的geohash值的比特大小来衡量。You can configure geospatial indexes with up to 32 bits of precision.您可以配置高达32位精度的地理空间索引。

Index precision does not affect query accuracy. 索引精度不影响查询精度。The actual grid coordinates are always used in the final query processing. 实际的网格坐标始终用于最终的查询处理。Advantages to lower precision are a lower processing overhead for insert operations and use of less space. 较低精度的优点是插入操作的处理开销较低,并且使用的空间较少。An advantage to higher precision is that queries scan smaller portions of the index to return results.更高精度的一个优点是查询扫描索引的较小部分以返回结果。

To configure a location precision other than the default, use the bits option when creating the index. 要配置默认值以外的位置精度,请在创建索引时使用bits选项。Use following syntax:使用以下语法:

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

For information on the internals of geohash values, see Calculation of Geohash Values for 2d Indexes.有关地理哈希值的内部信息,请参阅计算2d索引的地理哈希数值

←  2d IndexesQuery a 2d Index →