Database Manual / CRUD Operations

Geospatial Queries地理空间查询

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

Compatibility兼容性

You can use geospatial queries for deployments hosted in the following environments:您可以对以下环境中托管的部署使用地理空间查询:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

For deployments hosted in MongoDB Atlas, you can run geospatial queries in the UI by using the query Filter bar or aggregation builder. To learn more, see Perform Geospatial Queries in Atlas.对于MongoDB Atlas中托管的部署,您可以使用查询筛选器栏或聚合构建器在UI中运行地理空间查询。要了解更多信息,请参阅在Atlas中执行地理空间查询

Geospatial Data空间数据

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

GeoJSON ObjectsGeoJSON对象

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(坐标)的字段,指定对象的坐标。
<field>: { type: <GeoJSON type> , coordinates: <coordinates> }

Important

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

  • Valid longitude values are between -180 and 180, both inclusive.有效的经度值介于-180180之间,包括-180和-180。
  • Valid latitude values are between -90 and 90, both inclusive.有效的纬度值介于-9090之间,包括-9090

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.在球体上计算GeoJSON对象的MongoDB地理空间查询;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. MongoDB supports spherical surface calculations on legacy coordinate pairs by using a 2dsphere index if you manually convert the data to the GeoJSON Point type.要计算欧几里德平面上的距离,请将位置数据存储为传统坐标对,并使用2d索引。如果您手动将数据转换为GeoJSON Point类型,MongoDB支持使用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之间,包括-180-180
  • 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 contain 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之间,包括-180和-180。
  • 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 geospatial queries. For more information on geospatial indexes, see Geospatial Indexes.MongoDB提供以下地理空间索引类型以支持地理空间查询。有关地理空间索引的详细信息,请参阅地理空间索引

2dsphere

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

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对象,要么是传统坐标对

Note

If you try to create an index on a field that contains an array of geoJSON points, the index build fails and returns the following error:如果尝试在包含geoJSON点数组的字段上创建索引,则索引构建失败并返回以下错误:

MongoServerError: Index build failed

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

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索引的更多信息,请参阅2d索引

Geospatial Queries地理空间查询

Note

Using a 2d index for queries on spherical data can return incorrect results or an error. For example, 2d indexes don't support spherical queries that wrap around the poles.使用2d索引查询球形数据可能会返回不正确的结果或错误。例如,2d索引不支持围绕极点的球形查询。

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

MongoDB provides the following geospatial query operators. For more details, including examples, see the respective reference pages.MongoDB提供以下地理空间查询运算符。有关更多详细信息,包括示例,请参阅相应的参考页面。

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

Note

Time series collections only support the $geoNear aggregation stage for sorting geospatial data from queries against 2dsphere indexes. 时间序列集合仅支持$geoNear聚合阶段,用于对2dsphere索引查询中的地理空间数据进行排序。You can't use $near and $nearSphere operators on time series collections不能在时间序列集合上使用$near$nearSphere运算符

Geospatial Aggregation Stage地理空间聚合阶段

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

Stage阶段Description描述
$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.需要地理空间索引

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).索引仅支持球面查询(即解释球面上几何图形的查询)。

2d indexes support flat queries (i.e. queries that interpret geometries on a flat surface) and some spherical queries. 索引支持平面查询(即解释平面上几何图形的查询)和一些球面查询。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)GeoJSON质心点在这一行和下一行,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)传统坐标2d索引)Flat平面的
$nearSphere (GeoJSON point, 2dsphere index)GeoJSON点,2dsphere索引)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)传统坐标2d索引)Spherical球形的Use GeoJSON points instead.请改用GeoJSON点。
$geoWithin : { $geometry: ... }Spherical球形的
$geoWithin : { $box: ... }Flat平面的
$geoWithin : { $polygon: ... }Flat平面的
$geoWithin : { $center: ... }Flat平面的
$geoWithin : { $centerSphere: ... }Spherical球形的
$geoIntersectsSpherical球形的
$geoNear aggregation stage (2dsphere index)Spherical球形的
$geoNear aggregation stage (2d index)Flat平面的

Perform Geospatial Queries in Atlas在Atlas中执行地理空间查询

Query Filter Bar查询筛选栏

You can use the MongoDB Atlas UI to perform geospatial queries in Atlas.您可以使用MongoDB Atlas UI在Atlas中执行地理空间查询。

1

Create an index创建索引

If your geospatial collection does not already have a geospatial index, you must create one.如果地理空间集合还没有地理空间索引,则必须创建一个。

  1. Select the database for the collection.选择集合的数据库。

    The main panel and Namespaces on the left side list the collections in the database.主面板和左侧的命名空间列出了数据库中的集合。

  2. Select the collection.选择集合。

    Select the collection that contains your geospatial data on the left-hand side or in the main panel. The main panel displays the Find, Indexes, and Aggregation views.在左侧或主面板中选择包含地理空间数据的集合。主面板显示“查找”、“索引”和“聚合”视图。

  3. Select the Index view.选择“索引”视图。

    When you open the Index view, Atlas displays any indexes that exist on the collection.打开“索引”视图时,Atlas将显示集合上存在的所有索引。

  4. Define the Index for the geo Type定义地理类型的索引

    Press the Create Index button.按下“创建索引”按钮。

    Define a geo Type index. Refer to How to Index GeoJSON Objects.定义地理类型索引。请参阅如何索引GeoJSON对象

2

Query the geospatial data查询地理空间数据

  1. Select the Find view.选择“查找”视图。

    From the collection that contains your geospatial data, select the Find tab to view your geospatial collection.从包含地理空间数据的集合中,选择“查找”选项卡以查看地理空间集合。

  2. Enter a query.输入查询。

    Enter a query in the Filter text box. Use any of the geospatial query operators to perform the relevant query on your geospatial data. A geospatial query might resemble:在“筛选器”文本框中输入查询。使用任何地理空间查询运算符对地理空间数据执行相关查询。地理空间查询可能类似于:

    {
    "coordinates": {
    $geoWithin: {
    $geometry: {
    type: "Polygon",
    coordinates: [
    [
    [-80.0, 10.00], [ -80.0, 9.00], [ -79.0, 9.0], [ -79.0, 10.00 ], [ -80.0, 10.0 ]
    ]
    ]
    }
    }
    }
    }
  3. Press the Apply button.按下应用按钮。

    Press the Apply button to apply your query. Atlas filters the geospatial data to show only documents that match your geospatial query.按“应用”按钮应用查询。Atlas筛选地理空间数据,仅显示与地理空间查询匹配的文档。

Aggregation聚合

You can create and execute aggregation pipelines to perform geospatial queries in the MongoDB Atlas UI.您可以在MongoDB Atlas UI中创建和执行聚合管道以执行地理空间查询。

1

Access the aggregation pipeline builder访问聚合管道生成器

  1. Select the database for the collection.选择集合的数据库。

    The main panel and Namespaces on the left side list the collections in the database.主面板和左侧的“命名空间”列出了数据库中的集合。

  2. Select the collection.选择集合。

    Select the collection that contains your geospatial data on the left-hand side or in the main panel. The main panel displays the Find, Indexes, and Aggregation views.在左侧或主面板中选择包含地理空间数据的集合。主面板显示“查找”、“索引”和“聚合”视图。

  3. Select the Aggregation view.选择聚合视图。

    When you first open the Aggregation view, Atlas displays an empty aggregation pipeline.当您第一次打开“聚合”视图时,Atlas会显示一个空的聚合管道。

2

Create your geospatial query aggregation pipeline创建地理空间查询聚合管道

  1. Select an aggregation stage.选择聚合阶段。

    Select an aggregation stage from the Select dropdown in the bottom-left panel.从左下角面板的“选择”下拉列表中选择聚合阶段。

    The toggle to the right of the dropdown dictates whether the stage is enabled.下拉菜单右侧的开关指示是否启用该阶段。

    Use the $geoNear stage to perform geospatial queries in your aggregation pipeline.使用$geoNear阶段在聚合管道中执行地理空间查询。

  2. Fill in your aggregation stage.填写聚合阶段。

    Fill in your stage with the appropriate values. If Comment Mode is enabled, the pipeline builder provides syntactic guidelines for your selected stage.用适当的值填充阶段。如果启用了注释模式,管道构建器将为您选择的阶段提供语法指南。

    As you modify your stage, Atlas updates the preview documents on the right based on the results of the current stage.当您修改阶段时,Atlas会根据当前阶段的结果更新右侧的预览文档。

    Your $geoNear stage may resemble:$geoNear阶段可能类似于:

    {
    near: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
    spherical: true,
    query: { category: "Parks" },
    distanceField: "calcDistance"
    }
  3. Run other pipeline stages as needed.根据需要运行其他管道阶段。

    Add stages as needed to complete your aggregation pipeline. You might add $out or $merge to write the results to a view or the current collection.根据需要添加阶段以完成聚合管道。您可以添加$out$merge,将结果写入视图或当前集合。

Examples示例

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

db.places.insertMany( [
{
name: "Central Park",
location: { type: "Point", coordinates: [ -73.97, 40.77 ] },
category: "Parks"
},
{
name: "Sara D. Roosevelt Park",
location: { type: "Point", coordinates: [ -73.9928, 40.7193 ] },
category: "Parks"
},
{
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 places collection above has a 2dsphere index. 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:上面的places集合有一个2dsphere索引。以下查询使用$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"
}
}
] )