定义
$nearSpecifies a point for which a geospatial query returns the documents from nearest to farthest. The
$nearoperator can specify either a GeoJSON point or legacy coordinate point.$near需要地理空间索引:如果使用传统坐标指定了点,则为 2d 索引。
To specify a GeoJSON point,
$nearoperator 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> } } } 重要
如果指定纬度和经度坐标,则先列出经度,然后列出纬度。
有效经度值介于
-180和180之间,两者均包括在内。有效纬度值介于
-90和90之间,两者均包括在内。
When specifying a GeoJSON point, you can use the optional
$minDistanceand$maxDistancespecifications to limit the$nearresults by distance in meters:$minDistance会将结果限制为与中心点至少相距指定距离的文档。$maxDistance将结果限制那些距离中心点最多指定距离的文档。
To specify a point using legacy coordinates,
$nearrequires 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
$maxDistancespecification to limit the$nearresults by distance in radians.$maxDistancelimits 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.
示例
GeoJSON 数据查询
重要
如果指定纬度和经度坐标,则先列出经度,然后列出纬度。
有效经度值介于
-180和180之间,两者均包括在内。有效纬度值介于
-90和90之间,两者均包括在内。
考虑一个有 2dsphere 索引的集合 places。
以下示例返回距指定 GeoJSON 点至少 1000 米、至多 5000 米的文档(按从最近到最远排序):
db.places.find( { location: { $near : { $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] }, $minDistance: 1000, $maxDistance: 5000 } } } )
查询传统坐标
重要
如果指定纬度和经度坐标,则先列出经度,然后列出纬度。
有效经度值介于
-180和180之间,两者均包括在内。有效纬度值介于
-90和90之间,两者均包括在内。
考虑一个有 2d 索引的集合 legacy2d。
以下示例将返回距指定传统坐标对最多 0.10 弧度的文档(按从最近到最远的顺序排序):
db.legacy2d.find( { location : { $near : [ -73.9667, 40.78 ], $maxDistance: 0.10 } } )