对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

$near(查询谓词运算操作符)

$near

Specifies a point for which a geospatial query returns the documents from nearest to farthest. The $near operator can specify either a GeoJSON point or legacy coordinate point.

$near 需要地理空间索引:

  • 如果指定了 GeoJSON 点,则为 2dsphere 索引。

  • 如果使用传统坐标指定了点,则为 2d 索引。

To specify a GeoJSON point, $near operator requires a 2dsphere index and has the following syntax:

{
<location field>: {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ <longitude> , <latitude> ]
},
$maxDistance: <distance in meters>,
$minDistance: <distance in meters>
}
}
}

重要

如果指定纬度和经度坐标,则先列出经度,然后列出纬度

  • 有效经度值介于 -180180 之间,两者均包括在内。

  • 有效纬度值介于 -9090 之间,两者均包括在内。

When specifying a GeoJSON point, you can use the optional $minDistance and $maxDistance specifications to limit the $near results by distance in meters:

  • $minDistance 会将结果限制为与中心点至少相距指定距离的文档。

  • $maxDistance 将结果限制那些距离中心点最多指定距离的文档。

To specify a point using legacy coordinates, $near requires a 2d index and has the following syntax:

{
$near: [ <x>, <y> ],
$maxDistance: <distance in radians>
}

When specifying a legacy coordinate, you can use the optional $maxDistance specification to limit the $near results by distance in radians. $maxDistance limits the results to those documents that are at most the specified distance from the center point.

You cannot combine the $near operator, which requires a special geospatial index, with a query operator or command that requires another special index. For example you cannot combine $near with the $text query.

The $near operator sorts documents by distance.

  • 如果您在查询中使用了 sort() 方法,MongoDB 会再一次执行排序操作,对匹配的文档重新排序。查询大型集合时,这可能会对查询性能产生负面影响。

  • 如果文档的顺序对您来说并不重要,可以考虑改用 $geoWithin 操作符,因为该操作符会返回未排序的结果。

  • $near 是一种匹配执行操作符,不允许在聚合管道中使用。

Starting in MongoDB 8.0, $near, $nearSphere, and $geoNear validate that the type of the specified GeoJSON points is Point. Any other input type returns an error.

重要

如果指定纬度和经度坐标,则先列出经度,然后列出纬度

  • 有效经度值介于 -180180 之间,两者均包括在内。

  • 有效纬度值介于 -9090 之间,两者均包括在内。

考虑一个有 2dsphere 索引的集合 places

以下示例返回距指定 GeoJSON 点至少 1000 米、至多 5000 米的文档(按从最近到最远排序):

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

重要

如果指定纬度和经度坐标,则先列出经度,然后列出纬度

  • 有效经度值介于 -180180 之间,两者均包括在内。

  • 有效纬度值介于 -9090 之间,两者均包括在内。

考虑一个有 2d 索引的集合 legacy2d

以下示例将返回距指定传统坐标对最多 0.10 弧度的文档(按从最近到最远的顺序排序):

db.legacy2d.find(
{ location : { $near : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }
)
给本页内容打分

在此页面上