翻译或纠错本页面

2d 索引

对于以二维平面上点的方式存储的数据,可以使用 2d 索引。在MongoDB2.2版及更早之前, 2d 索引是用于索引普通坐标。

使用 2d 索引, 在如下情况:

  • 您的数据库中存储的是从MongoDB2.2版或者更早版遗留下的普通位置信息, 并且

  • 您不打算把位置数据存储为 GeoJSON 对象。

参见 Geospatial Query Operators 来了解支持地理查询的操作符。

注意事项

The geoNear command and the $geoNear pipeline stage require that a collection have at most only one 2d index and/or only one 2dsphere index whereas geospatial query operators (e.g. $near and $geoWithin) permit collections to have multiple geospatial indexes.

The geospatial index restriction for the geoNear command and the $geoNear pipeline stage exists because neither the geoNear command nor the $geoNear pipeline stage syntax includes the location field. As such, index selection among multiple 2d indexes or 2dsphere indexes is ambiguous.

No such restriction applies for geospatial query operators since these operators take a location field, eliminating the ambiguity.

请不要使用 2d 索引, 如果您的位置信息里包含GeoJSON对象。如果要同时索引普通坐标 GeoJSON对象,请使用 2dsphere 索引。

当把一个集合分片时, 您不应该使用 2d 索引键作为分片键。 但是,在使用其他键作为分片键的前提下, 您可以在被分片的集合上创建并维护一个地理索引。

特性

MongoDB中 2d 索引支持在欧几里德平面上的计算。 2d 索引也支持在球面上 distance-only 计算。但是如果是在球面上的 地理 计算(例如 :query: :$geoWithin) ,请把数据存储为GeoJSON对象,并使用 2dsphere 索引。

MongoDB中 2d 复合索引可以包含两个键。第一个键必须是位置键。在查询时, 2d 复合索引首先根据位置键选择文档,然后再根据附加的第二个键过滤结果集。复合 2d 索引可以覆盖查询(这意味着,不需要载入文档而直接返回结果)。

在二维平面上的点

可以通过数据或者子文档的形式,把位置数据存储为普通坐标。如果可以,请使用数组格式:

loc : [ <longitude> , <latitude> ]

以下是子文档格式:

loc : { lng : <longitude> , lat : <latitude> }

更推荐数组是因为某些语言也许无法保证关联字典顺序。

如果是以经度和纬度定位的点,请存储为 经度,纬度 顺序。

稀疏 属性

默认情况下, 2d 索引是 稀疏 的,并且忽略 sparse: true 选项。如果一篇文档中不包含 2d 索引键(或者这个键存储的是 null 或者空数组),那么MongoDB将不会为这篇文档建立 2d 索引项。如果是一个插入操作,MongoDB会插入这篇文档,但不把它加到 2d 索引中。

For a compound index that includes a 2d index key along with keys of other types, only the 2d index field determines whether the index references a document.