定义
$geoWithin选择地理空间数据完全位于指定形状内的文档。
The specified shape can be either a GeoJSON
Polygon(either single-ringed or multi-ringed), a GeoJSONMultiPolygon, or a shape defined by legacy coordinate pairs. The$geoWithinoperator uses the$geometryoperator to specify the GeoJSON object.要使用默认坐标参考系 (CRS) 指定 GeoJSON 多边形或多多边形,请使用以下语法:
{ <location field>: { $geoWithin: { $geometry: { type: <"Polygon" or "MultiPolygon"> , coordinates: [ <coordinates> ] } } } } For
$geoWithinqueries that specify GeoJSON geometries with areas greater than a single hemisphere, the use of the default CRS results in queries for the complementary geometries.要使用自定义 MongoDB CRS 指定单环 GeoJSON 多边形,请在
$geometry表达式中使用指定自定义 MongoDB CRS 的原型:{ <location field>: { $geoWithin: { $geometry: { type: "Polygon" , coordinates: [ <coordinates> ], crs: { type: "name", properties: { name: "urn:x-mongodb:crs:strictwinding:EPSG:4326" } } } } } } The custom MongoDB CRS uses a counter-clockwise winding order and allows
$geoWithinto support queries with a single-ringed GeoJSON polygon whose area is greater than or equal to a single hemisphere. If the specified polygon is smaller than a single hemisphere, the behavior of$geoWithinwith the MongoDB CRS is the same as with the default CRS. See also "Big" Polygons.如果查询是否包含在由平面上的传统坐标对定义的形状中,请使用以下事务语法:
{ <location field>: { $geoWithin: { <shape operator>: <coordinates> } } } 可用形状操作符包括:
$center(定义一个圆),且$centerSphere(在球体上定义一个圆)。
重要
如果使用经度和纬度,请按照
longitude, latitude的顺序指定坐标。
行为
地理空间索引
$geoWithin不需要地理空间索引。但是,地理空间索引可提高查询性能。2 dsphere 和2 d地理空间索引都支持 $geoWithin。
未排序的结果
The $geoWithin operator does not return sorted results. As such, MongoDB can return $geoWithin queries more quickly than geospatial $near or $nearSphere queries, which sort results.
退化几何图形
$geoWithin 不保证它会考虑一个几何体来纳入其组件几何体,或另一个共享其组件几何体的多边形。
“大”多边形
For $geoWithin, if you specify a single-ringed polygon that has an area greater than a single hemisphere, include the custom MongoDB coordinate reference system in the $geometry expression. Otherwise, $geoWithin queries for the complementary geometry. For all other GeoJSON polygons with areas greater than a hemisphere, $geoWithin queries for the complementary geometry.
示例
在多边形内
以下示例选择了完全存在于 GeoJSON Polygon 中的所有 loc 数据。 多边形的面积小于单半球的面积:
db.places.find( { loc: { $geoWithin: { $geometry: { type : "Polygon" , coordinates: [ [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ] ] ] } } } } )
对于面积大于单半球的单环多边形,请参阅在“大型”多边形内。
在“大型”多边形内
如需使用面积大于单个半球的单环 GeoJSON 多边形进行查询,$geometry 表达式必须指定自定义 MongoDB 坐标参考系。例如:
db.places.find( { loc: { $geoWithin: { $geometry: { type : "Polygon" , coordinates: [ [ [ -100, 60 ], [ -100, 0 ], [ -100, -60 ], [ 100, -60 ], [ 100, 60 ], [ -100, 60 ] ] ], crs: { type: "name", properties: { name: "urn:x-mongodb:crs:strictwinding:EPSG:4326" } } } } } } )