Geospatial Queries地理空间查询

On this page本页内容

MongoDB supports query operations on geospatial data. MongoDB支持对地理空间数据的查询操作。This section introduces MongoDB’s geospatial features.本节介绍MongoDB的地理空间功能。

Geospatial Data空间数据

In MongoDB, you can store geospatial data as GeoJSON objects or as legacy coordinate pairs.在MongoDB中,可以将地理空间数据存储为GeoJSON对象或传统坐标对

GeoJSON Objects

To calculate geometry over an Earth-like sphere, store your location data as GeoJSON objects.要计算类地球球体上的几何体,请将位置数据存储为GeoJSON对象

To specify GeoJSON data, use an embedded document with:要指定GeoJSON数据,请使用带有以下内容的嵌入式文档:

  • a field named type that specifies the GeoJSON object type and名为type的字段,指定GeoJSON对象类型,以及
  • a field named coordinates that specifies the object’s coordinates.名为coordinates的字段,用于指定对象的坐标。

    If specifying latitude and longitude coordinates, list the longitude first and then latitude:如果指定纬度和经度坐标,请先列出经度,然后列出纬度

    • Valid longitude values are between -180 and 180, both inclusive.有效的经度值介于-180180之间(包括-180180)。
    • Valid latitude values are between -90 and 90, both inclusive.有效纬度值介于-9090之间(包括-9090)。
<field>: { type: <GeoJSON type> , coordinates: <coordinates> }

For example, to specify a GeoJSON Point:例如,要指定GeoJSON点

location: {
      type: "Point",
      coordinates: [-73.856077, 40.848447]
}

For a list of the GeoJSON objects supported in MongoDB as well as examples, see GeoJSON objects.有关MongoDB中支持的GeoJSON对象的列表以及示例,请参阅GeoJSON对象

MongoDB geospatial queries on GeoJSON objects calculate on a sphere; MongoDB uses the WGS84 reference system for geospatial queries on GeoJSON objects.MongoDB对GeoJSON对象的地理空间查询在球体上计算;MongoDB使用WGS84参考系统对GeoJSON对象进行地理空间查询。

Legacy Coordinate Pairs传统坐标对

To calculate distances on a Euclidean plane, store your location data as legacy coordinate pairs and use a 2d index. 要计算欧几里德平面上的距离,请将位置数据存储为传统坐标对,并使用2d索引。MongoDB supports spherical surface calculations on legacy coordinate pairs via a 2dsphere index by converting the data to the GeoJSON Point type.MongoDB通过将数据转换为GeoJSON点类型,通过2dsphere索引支持传统坐标对的球面计算。

To specify data as legacy coordinate pairs, you can use either an array (preferred) or an embedded document.要将数据指定为传统坐标对,可以使用数组(首选)或嵌入式文档。

Specify via an array (Preferred):通过数组指定(首选):
<field>: [ <x>, <y> ]

If specifying latitude and longitude coordinates, list the longitude first and then latitude; i.e.如果指定纬度和经度坐标,请先列出经度,然后列出纬度;即

<field>: [<longitude>, <latitude> ]
  • Valid longitude values are between -180 and 180, both inclusive.有效的经度值介于-180180之间,两者都包括在内。
  • Valid latitude values are between -90 and 90, both inclusive.有效纬度值介于-9090之间(包括-9090)。
Specify via an embedded document:通过嵌入文档指定:
<field>: { <field1>: <x>, <field2>: <y> }

If specifying latitude and longitude coordinates, the first field, regardless of the field name, must contains the longitude value and the second field, the latitude value ; i.e.如果指定纬度和经度坐标,无论字段名称如何,第一个字段必须包含经度值,第二个字段必须包含纬度值;即

<field>: { <field1>: <longitude>, <field2>: <latitude> }
  • Valid longitude values are between -180 and 180, both inclusive.有效的经度值介于-180180之间(包括-180180)。
  • Valid latitude values are between -90 and 90, both inclusive.有效纬度值介于-9090之间(包括-9090)。

To specify legacy coordinate pairs, arrays are preferred over an embedded document as some languages do not guarantee associative map ordering.要指定传统坐标对,数组优先于嵌入式文档,因为某些语言不能保证关联地图顺序。

Geospatial Indexes地理空间索引

MongoDB provides the following geospatial index types to support the geospatial queries.MongoDB提供以下地理空间索引类型以支持地理空间查询。

2dsphere

2dsphere indexes support queries that calculate geometries on an earth-like sphere.2dsphere索引支持在类地球球体上计算几何图形的查询。

To create a 2dsphere index, use the db.collection.createIndex() method and specify the string literal "2dsphere" as the index type:要创建2dsphere索引,请使用db.collection.createIndex()方法,并将字符串文本"2dsphere"指定为索引类型:

db.collection.createIndex( { <location field> : "2dsphere" } )

where the <location field> is a field whose value is either a GeoJSON object or a legacy coordinates pair.其中,<location field>是一个值为GeoJSON对象遗留坐标对的字段。

For more information on the 2dsphere index, see 2dsphere Indexes.有关2dsphere索引的更多信息,请参阅2dsphere索引

2d

2d indexes support queries that calculate geometries on a two-dimensional plane. 2d索引支持在二维平面上计算几何图形的查询。Although the index can support $nearSphere queries that calculate on a sphere, if possible, use the 2dsphere index for spherical queries.虽然该索引可以支持在球体上计算的$nearSphere查询,但如果可能,请使用2dsphere索引进行球体查询。

To create a 2d index, use the db.collection.createIndex() method, specifying the location field as the key and the string literal "2d" as the index type:要创建2d索引,请使用db.collection.createIndex()方法,将位置字段指定为键,将字符串文字"2d"指定为索引类型:

db.collection.createIndex( { <location field> : "2d" } )

where the <location field> is a field whose value is a legacy coordinates pair.其中,<location field>是一个值为传统坐标对的字段。

For more information on the 2d index, see 2d Indexes.有关二维索引的详细信息,请参阅2d索引

Geospatial Indexes and Sharded Collections地理空间索引和分片集合

You cannot use a geospatial index as a shard key when sharding a collection. 切分集合时,不能将地理空间索引用作切分键However, you can create a geospatial index on a sharded collection by using a different field as the shard key.但是,可以使用其他字段作为分片键,在分片集合上创建地理空间索引。

The following geospatial operations are supported on sharded collections:分片集合支持以下地理空间操作:

Starting in MongoDB 4.0, $near and $nearSphere queries are supported for sharded collections.从MongoDB 4.0开始,分片集合支持$near$nearSphere查询。

In earlier MongoDB versions, $near and $nearSphere queries are not supported for sharded collections; instead, for sharded clusters, you must use the $geoNear aggregation stage or the geoNear command (available in MongoDB 4.0 and earlier).在早期的MongoDB版本中,分片集合不支持$near$nearSphere查询;相反,对于分片集群,必须使用$geoNear聚合阶段或geoNear命令(在MongoDB 4.0及更早版本中提供)。

You can also query for geospatial data for a sharded cluster using $geoWithin and $geoIntersect.还可以使用$geoWithin$geoIntersect查询分片集群的地理空间数据。

Covered Queries覆盖查询

Geospatial indexes cannot cover a query.地理空间索引不能覆盖查询

Geospatial Queries地理空间查询

Note

For spherical queries, use the 2dsphere index result.对于球形查询,请使用2dsphere索引结果。

The use of 2d index for spherical queries may lead to incorrect results, such as the use of the 2d index for spherical queries that wrap around the poles.对球形查询使用2d索引可能会导致错误的结果,例如对环绕极点的球形查询使用2d索引。

Geospatial Query Operators地理空间查询运算符

MongoDB provides the following geospatial query operators:MongoDB提供以下地理空间查询运算符:

Name名称Description描述
$geoIntersects Selects geometries that intersect with a GeoJSON geometry. 选择与GeoJSON几何图形相交的几何图形。The 2dsphere index supports $geoIntersects.2dsphere索引支持$geoIntersects
$geoWithin Selects geometries within a bounding GeoJSON geometry. 选择边界GeoJSON几何图形中的几何图形。The 2dsphere and 2d indexes support $geoWithin.2dsphere2d索引支持$geoWithin
$near Returns geospatial objects in proximity to a point. 返回点附近的地理空间对象。Requires a geospatial index. 需要地理空间索引。The 2dsphere and 2d indexes support $near.2dsphere2d索引支持$near
$nearSphere Returns geospatial objects in proximity to a point on a sphere. 返回球体上某个点附近的地理空间对象。Requires a geospatial index. 需要地理空间索引。The 2dsphere and 2d indexes support $nearSphere.

For more details, including examples, see the individual reference page.有关更多详细信息(包括示例),请参阅个人参考页。

Geospatial Aggregation Stage地理空间聚合阶段

MongoDB provides the following geospatial aggregation pipeline stage:MongoDB提供以下地理空间聚合管道阶段

StageDescription描述
$geoNear

Returns an ordered stream of documents based on the proximity to a geospatial point. 根据与地理空间点的接近程度返回有序的文档流。Incorporates the functionality of $match, $sort, and $limit for geospatial data. 合并了地理空间数据的$match$sort$limit功能。The output documents include an additional distance field and can include a location identifier field.输出文档包括一个额外的距离字段,还可以包括一个位置标识符字段。

$geoNear requires a geospatial index.$geoNear需要地理空间索引

For more details, including examples, see $geoNear reference page.有关更多详细信息(包括示例),请参阅$geoNear参考页。

Geospatial Models地理空间模型

MongoDB geospatial queries can interpret geometry on a flat surface or a sphere.MongoDB地理空间查询可以解释平面或球体上的几何图形。

2dsphere indexes support only spherical queries (i.e. queries that interpret geometries on a spherical surface).2dsphere索引只支持球形查询(即解释球面上几何图形的查询)。

2d indexes support flat queries (i.e. queries that interpret geometries on a flat surface) and some spherical queries. 2d索引支持平面查询(即解释平面上几何图形的查询)和一些球形查询。While 2d indexes support some spherical queries, the use of 2d indexes for these spherical queries can result in error. 虽然2d索引支持一些球形查询,但对这些球形查询使用2d索引可能会导致错误。If possible, use 2dsphere indexes for spherical queries.如果可能,使用2dsphere索引进行球形查询。

The following table lists the geospatial query operators, supported query, used by each geospatial operations:下表列出了每个地理空间操作所使用的地理空间查询运算符(支持的查询):

Operation活动Spherical/Flat Query球面/平面查询Notes备注
$near (GeoJSON centroid point in this line and the following line, 2dsphere index)这条线和下一条线的质心点(2dsphere索引) Spherical See also the $nearSphere operator, which provides the same functionality when used with GeoJSON and a 2dsphere index.另请参见$nearSphere运算符,它在与GeoJSON2dsphere索引一起使用时提供相同的功能。
$near (legacy coordinates, 2d index) Flat  
$nearSphere (GeoJSON point, 2dsphere index) Spherical

Provides the same functionality as $near operation that uses GeoJSON point and a 2dsphere index.提供与使用GeoJSON点和2dsphere索引的$near操作相同的功能。

For spherical queries, it may be preferable to use $nearSphere which explicitly specifies the spherical queries in the name rather than $near operator.对于球形查询,最好使用$nearSphere,它在名称中显式指定球形查询,而不是$near运算符。

$nearSphere (legacy coordinates, 2d index) Spherical Use GeoJSON points instead.改用GeoJSON点。
$geoWithin : { $geometry: … } Spherical  
$geoWithin : { $box: … } Flat  
$geoWithin : { $polygon: … } Flat  
$geoWithin : { $center: … } Flat  
$geoWithin : { $centerSphere: … } Spherical  
$geoIntersects Spherical  
$geoNear aggregation stage (2dsphere index)$geoNear聚合阶段(2dsphere索引) Spherical  
$geoNear aggregation stage (2d index)聚合阶段(2d索引) Flat  

Example示例

Create a collection places with the following documents:使用以下文档创建集合places

db.places.insert( {
    name: "Central Park",
   location: { type: "Point", coordinates: [ -73.97, 40.77 ] },
   category: "Parks"
} );
db.places.insert( {
   name: "Sara D. Roosevelt Park",
   location: { type: "Point", coordinates: [ -73.9928, 40.7193 ] },
   category: "Parks"
} );
db.places.insert( {
   name: "Polo Grounds",
   location: { type: "Point", coordinates: [ -73.9375, 40.8303 ] },
   category: "Stadiums"
} );

The following operation creates a 2dsphere index on the location field:以下操作将在location字段上创建2dsphere索引:

db.places.createIndex( { location: "2dsphere" } )

The following query uses the $near operator to return documents that are at least 1000 meters from and at most 5000 meters from the specified GeoJSON point, sorted in order from nearest to farthest:以下查询使用$near运算符返回距离指定GeoJSON点至少1000米、最多5000米的文档,按从最近到最远的顺序排序:

db.places.find(
   {
     location:
       { $near:
          {
            $geometry: { type: "Point",  coordinates: [ -73.9667, 40.78 ] },
            $minDistance: 1000,
            $maxDistance: 5000
          }
       }
   }
)

The following operation uses the geoNear aggregation operation to return documents that match the query filter { category: "Parks" }, sorted in order of nearest to farthest to the specified GeoJSON point:以下操作使用geoNear聚合操作返回与查询筛选器{ category: "Parks" }匹配的文档,并按距离指定GeoJSON点最近到最远的顺序进行排序:

db.places.aggregate( [
   {
      $geoNear: {
         near: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
         spherical: true,
         query: { category: "Parks" },
         distanceField: "calcDistance"
      }
   }
] )