$geoNear (aggregation)
On this page本页内容
Definition定义
$geoNear
-
Outputs documents in order of nearest to farthest from a specified point.按离指定点最近到最远的顺序输出文档。NoteStarting in version 4.2, MongoDB removes the从4.2版本开始,MongoDB删除了limit
andnum
options for the$geoNear
stage as well as the default limit of 100 documents.$geoNear
阶段的limit
和num
选项,以及100个文档的默认限制。To limit the results of若要限制$geoNear
, use the$geoNear
stage with the$limit
stage.$geoNear
的结果,请将$geoNear
阶段与$limit
阶段一起使用。The$geoNear
stage has the following prototype form:$geoNear
阶段具有以下原型形式:{ $geoNear: { <geoNear options> } }
The$geoNear
operator accepts a document that contains the following$geoNear
options. Specify all distances in the same units as those of the processed documents' coordinate system:$geoNear
运算符接受包含以下$geoNeal
选项的文档。以与已处理文档坐标系相同的单位指定所有距离:Field字段Type类型Description描述distanceField
string The output field that contains the calculated distance.包含计算距离的输出字段。To specify a field within an embedded document, use dot notation.若要在嵌入文档中指定字段,请使用点表示法。distanceMultiplier
number Optional.可选的。The factor to multiply all distances returned by the query.乘以查询返回的所有距离的因子。For example, use the例如,使用distanceMultiplier
to convert radians, as returned by a spherical query, to kilometers by multiplying by the radius of the Earth.distanceMultiplier
将球面查询返回的弧度乘以地球半径,转换为千米。includeLocs
string Optional.可选的。This specifies the output field that identifies the location used to calculate the distance.这指定了用于标识用于计算距离的位置的输出字段。This option is useful when a location field contains multiple locations.当位置字段包含多个位置时,此选项非常有用。To specify a field within an embedded document, use dot notation.若要在嵌入文档中指定字段,请使用点表示法。key
Optional.可选的。Specify the geospatial indexed field to use when calculating the distance.指定计算距离时要使用的地理空间索引字段。
If your collection has multiple如果集合具有多个2d
and/or multiple2dsphere
indexes, you must use thekey
option to specify the indexed field path to use.2d
和/或多个2dsphere
索引,则必须使用键选项指定要使用的索引字段路径。Specify Which Geospatial Index to Use provides a full example.指定要使用的地理空间索引提供了一个完整的示例。
If there is more than one如果有多个2d
index or more than one2dsphere
index and you do not specify akey
, MongoDB will return an error.2d
索引或多个2dsphere
索引,并且您没有指定key
,MongoDB将返回错误。
If you do not specify the如果您没有指定key
, and you have at most only one2d
index and/or only one2dsphere
index, MongoDB looks first for a2d
index to use. If a2d
index does not exists, then MongoDB looks for a2dsphere
index to use.key
,并且最多只有一个2d
索引和/或只有一个2dsphere
索引,MongoDB会首先查找要使用的2d
索引。如果2d
索引不存在,那么MongoDB会查找要使用的2dsphere
索引。maxDistance
number Optional.可选的。The maximum distance from the center point that the documents can be.距文档中心点的最大距离。MongoDB limits the results to those documents that fall within the specified distance from the center point.MongoDB将结果限制在距离中心点指定距离内的文档。
Specify the distance in meters if the specified point is GeoJSON and in radians if the specified point is legacy coordinate pairs.如果指定点为GeoJSON,则以米为单位指定距离;如果指定点是遗留坐标对,则以弧度为单位指定。minDistance
number Optional.可选的。The minimum distance from the center point that the documents can be.离文档中心点的最小距离。MongoDB limits the results to those documents that fall outside the specified distance from the center point.MongoDB将结果限制在距离中心点指定距离之外的文档。
Specify the distance in meters for GeoJSON data and in radians for legacy coordinate pairs.为GeoJSON数据指定以米为单位的距离,为旧坐标对指定以弧度为单位的间距。near
GeoJSON point or legacy coordinate pairGeoJSON点或遗留坐标对The point for which to find the closest documents.查找最接近文档的点。
If using a 2dsphere index, you can specify the point as either a GeoJSON point or legacy coordinate pair.如果使用2dsphere
索引,则可以将该点指定为GeoJSON点或传统坐标对。
If using a 2d index, specify the point as a legacy coordinate pair.如果使用2d
索引,请将该点指定为传统坐标对。query
document Optional.可选的。Limits the results to the documents that match the query.将结果限制为与查询匹配的文档。The query syntax is the usual MongoDB read operation query syntax.查询语法是通常的MongoDB读取操作查询语法。
You cannot specify a不能在$near
predicate in thequery
field of the$geoNear
stage.$geoNear
阶段的查询字段中指定$near
谓词。spherical
boolean Optional.可选的。Determines how MongoDB calculates the distance between two points:确定MongoDB如何计算两点之间的距离:When当为true
, MongoDB uses$nearSphere
semantics and calculates distances using spherical geometry.true
时,MongoDB使用$nearSphere
语义,并使用球形几何体计算距离。When当为false
, MongoDB uses$near
semantics: spherical geometry for 2dsphere indexes and planar geometry for 2d indexes.false
时,MongoDB使用$near
语义:球形几何体用于2dsphere
索引,平面几何体用于2d
索引。
Default: false.默认值:false
。
Behavior行为
When using 使用$geoNear
, consider that:$geoNear
时,请考虑:
You can only use您只能将$geoNear
as the first stage of a pipeline.$geoNear
用作管道的第一阶段。You must include the必须包含distanceField
option. ThedistanceField
option specifies the field that will contain the calculated distance.distanceField
选项。distanceField
选项指定将包含计算距离的字段。$geoNear
requires a geospatial index.需要地理空间索引。If you have more than one geospatial index on the collection, use the如果集合中有多个地理空间索引,请使用keys
parameter to specify which field to use in the calculation. If you have only one geospatial index,$geoNear
implicitly uses the indexed field for the calculation.keys
参数指定要在计算中使用的字段。如果只有一个地理空间索引,$geoNear
将隐式使用索引字段进行计算。
You cannot specify a不能在$near
predicate in thequery
field of the$geoNear
stage.$geoNear
阶段的query
字段中指定$near
谓词。Views do not support geoNear operations (specifically, the视图不支持$geoNear
pipeline stage).$geoNear
操作(特别是$geoNear
管道阶段)。Starting in version 4.2,从4.2版本开始,$geoNear
no longer has a default limit of 100 documents.$geoNear
不再默认限制为100个文档。Starting in MongoDB 5.1, the从MongoDB 5.1开始,near
parameter supports the let option and bound let option.near
参数支持let
选项和边界let
选项。Starting in MongoDB 5.3, you can use the从MongoDB 5.3开始,您可以在时间序列集合中的任何字段上使用$geoNear
pipeline operator on any field in a time series collection.$geoNear
管道运算符。Starting in MongoDB 6.0, you can create partial and 2dsphere indexes on any field in a time series collection.从MongoDB 6.0开始,您可以在时间序列集合中的任何字段上创建partial
索引和2dsphere
索引。
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" } )
Maximum Distance最大距离
Starting in version 4.2, MongoDB removes the 从4.2版本开始,MongoDB删除了limit
and num
options for the $geoNear
stage as well as the default limit of 100 documents. To limit the results of $geoNear
, use the $geoNear
stage with the $limit
stage.$geoNear
阶段的limit
和num
选项,以及100个文档的默认限制。若要限制$geoNear
的结果,请将$geoNear
阶段与$limit
阶段一起使用。
The 上面的places
collection above has a 2dsphere
index. places
集合有一个2dsphere
索引。The following aggregation uses 以下聚合使用$geoNear
to find documents with a location at most 2 meters from the center [ -73.99279 , 40.719296 ]
and category
equal to Parks
.$geoNear
查找位置距离中心[ -73.99279 , 40.719296 ]
最多2米且category
等于Parks
的文档。
db.places.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
distanceField: "dist.calculated",
maxDistance: 2,
query: { category: "Parks" },
includeLocs: "dist.location",
spherical: true
}
}
])
The aggregation returns the following:聚合返回以下内容:
{
"_id" : 8,
"name" : "Sara D. Roosevelt Park",
"category" : "Parks",
"location" : {
"type" : "Point",
"coordinates" : [ -73.9928, 40.7193 ]
},
"dist" : {
"calculated" : 0.9539931676365992,
"location" : {
"type" : "Point",
"coordinates" : [ -73.9928, 40.7193 ]
}
}
}
The matching document contains two new fields:匹配的文档包含两个新字段:
dist.calculated
field that contains the calculated distance, and包含计算距离的字段,以及dist.location
field that contains the location used in the calculation.包含计算中使用的位置的字段。
Minimum Distance最小距离
Starting in version 4.2, MongoDB removes the 从4.2版本开始,MongoDB删除了limit
and num
options for the $geoNear
stage as well as the default limit of 100 documents. $geoNear
阶段的limit
和num
选项,以及100个文档的默认限制。To limit the results of 若要限制$geoNear
, use the $geoNear
stage with the $limit
stage.$geoNear
的结果,请将$geoNear
阶段与$limit
阶段一起使用。
The following example uses the option 以下示例使用选项minDistance
to specify the minimum distance from the center point that the documents can be. minDistance
来指定与文档可能位于的中心点的最小距离。The following aggregation finds all documents with a location at least 2 meters from the center 以下聚合查找位置距离中心[ -73.99279 , 40.719296 ]
and category
equal to Parks
.[ -73.99279 , 40.719296 ]
至少2米且category
等于Parks
的所有文档。
db.places.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
distanceField: "dist.calculated",
minDistance: 2,
query: { category: "Parks" },
includeLocs: "dist.location",
spherical: true
}
}
])
$geoNear with the let
option带有let
选项的$geoNear
let
optionIn this example:在本例中:
Thelet选项用于将数组值let
option is used to set an array value of[-73.99279,40.719296]
to the variable$pt
.[-73.99279,40.719296]
设置为变量$pt
。$pt
is specified as a let option to the被指定为near
parameter in the$geoNear
stage.$geoNear
阶段中near
参数的let
选项。
db.places.aggregate(
[
{
"$geoNear":
{
"near":"$$pt",
"distanceField":"distance",
"maxDistance":2,
"query":{"category":"Parks"},
"includeLocs":"dist.location",
"spherical":true
}
}
],
{
"let":{ "pt": [ -73.99279, 40.719296 ] }
}
)
The aggregation returns all documents with:聚合返回所有文档,其中包含:
A location at most 2 meters from the point defined in the距离let
variablelet
变量中定义的点最多2米的位置A一个等于category
equal toParks
.Parks
的category
。
{
_id: ObjectId("61715cf9b0c1d171bb498fd7"),
name: 'Sara D. Roosevelt Park',
location: { type: 'Point', coordinates: [ -73.9928, 40.7193 ] },
category: 'Parks',
distance: 1.4957325341976439e-7,
dist: { location: { type: 'Point', coordinates: [ -73.9928, 40.7193 ] } }
},
{
_id: ObjectId("61715cf9b0c1d171bb498fd6"),
name: 'Central Park',
location: { type: 'Point', coordinates: [ -73.97, 40.77 ] },
category: 'Parks',
distance: 0.0009348548688841822,
dist: { location: { type: 'Point', coordinates: [ -73.97, 40.77 ] } }
}
$geoNear with Bound let
Option$geoNear
与边界let
选项
let
OptionThe let
option can bind a variable which can be used in a $geoNear query.let
选项可以绑定一个变量,该变量可以在$geoNear
查询中使用。
In this example, 在本例中,$lookup
uses:$lookup
使用:
let
to define$pt
.let
用来定义$pt
。$geoNear
in thepipeline
.pipeline
中的$geoNear
。$pt
to define用来定义near
in the$geoNear
pipeline stage.$geoNear
管道阶段中的near
db.places.aggregate( [
{
$lookup: {
from: "places",
let: { pt: "$location" },
pipeline: [
{
$geoNear: {
near: "$$pt",
distanceField: "distance"
}
}
],
as: "joinedField"
}
},
{
$match: { name: "Sara D. Roosevelt Park" }
}
] );
The aggregation returns a document with:聚合返回一个文档,其中包含:
The 'Sara D. Roosevelt Park' document as the main document.以“萨拉·D·罗斯福公园”文件为主要文档。Every document in the places collection as subDocuments using theplaces集合中的每个文档都是使用$pt
variable for calculating distance.$pt
变量计算距离的子文档。
{
_id: ObjectId("61715cf9b0c1d171bb498fd7"),
name: 'Sara D. Roosevelt Park',
location: { type: 'Point', coordinates: [ -73.9928, 40.7193 ] },
category: 'Parks',
joinedField: [
{
_id: ObjectId("61715cf9b0c1d171bb498fd7"),
name: 'Sara D. Roosevelt Park',
location: { type: 'Point', coordinates: [ -73.9928, 40.7193 ] },
category: 'Parks',
distance: 0
},
{
_id: ObjectId("61715cf9b0c1d171bb498fd6"),
name: 'Central Park',
location: { type: 'Point', coordinates: [ -73.97, 40.77 ] },
category: 'Parks',
distance: 5962.448255234964
},
{
_id: ObjectId("61715cfab0c1d171bb498fd8"),
name: 'Polo Grounds',
location: { type: 'Point', coordinates: [ -73.9375, 40.8303 ] },
category: 'Stadiums',
distance: 13206.535424939102
}
]
}
Specify Which Geospatial Index to Use指定要使用的地理空间索引
Consider a 考虑一个places
collection that has a 2dsphere index on the location
field and a 2d index on the legacy
field.places
集合,该集合在location
字段上具有2dsphere
索引,在legacy
字段上有2d
索引。
A document in the places
collection resembles the following:places
集合中的文档类似于以下内容:
{
"_id" : 3,
"name" : "Polo Grounds",
"location": {
"type" : "Point",
"coordinates" : [ -73.9375, 40.8303 ]
},
"legacy" : [ -73.9375, 40.8303 ],
"category" : "Stadiums"
}
The following example uses the 以下示例使用key
option to specify that the aggregation should use the location
field values for the $geoNear
operation rather than the legacy
field values. key
选项指定聚合应使用$geoNear
操作的location
字段值,而不是旧字段值。The pipeline also uses 该管道还使用$limit
to return at most 5 documents.$limit
返回最多5个文档。
Starting in version 4.2, MongoDB removes the 从4.2版本开始,MongoDB删除了limit
and num
options for the $geoNear
stage as well as the default limit of 100 documents. $geoNear
阶段的limit
和num
选项,以及100个文档的默认限制。To limit the results of 若要限制$geoNear
, use the $geoNear
stage with the $limit
stage.$geoNear
的结果,请将$geoNear
阶段与$limit
阶段一起使用。
db.places.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ -73.98142 , 40.71782 ] },
key: "location",
distanceField: "dist.calculated",
query: { "category": "Parks" }
}
},
{ $limit: 5 }
])
The aggregation returns the following:聚合返回以下内容:
{
"_id" : 8,
"name" : "Sara D. Roosevelt Park",
"location" : {
"type" : "Point",
"coordinates" : [
-73.9928,
40.7193
]
},
"category" : "Parks",
"dist" : {
"calculated" : 974.175764916902
}
}
{
"_id" : 1,
"name" : "Central Park",
"location" : {
"type" : "Point",
"coordinates" : [
-73.97,
40.77
]
},
"legacy" : [
-73.97,
40.77
],
"category" : "Parks",
"dist" : {
"calculated" : 5887.92792958097
}
}