Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$geoWithin

在此页面上

  • 定义
  • 行为
  • 举例
$geoWithin

选择地理空间数据完全位于指定形状内的文档。

指定的形状可以是 GeoJSON Polygon (单环或多环)、GeoJSON MultiPolygon或由传统坐标对定义的形状。 $geoWithin操作符使用$geometry操作符来指定GeoJSON对象。

要使用默认坐标参考系 (CRS) 指定 GeoJSON 多边形或多多边形,请使用以下语法:

{
<location field>: {
$geoWithin: {
$geometry: {
type: <"Polygon" or "MultiPolygon"> ,
coordinates: [ <coordinates> ]
}
}
}
}

对于指定面积大于单个半球的 GeoJSON 几何图形的$geoWithin查询,使用默认 CRS 会导致查询互补几何图形。

要使用自定义 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" }
}
}
}
}
}

自定义 MongoDB CRS 使用逆时针缠绕顺序,并允许$geoWithin支持使用面积大于或等于单个半球的单环 GeoJSON多边形进行查询。如果指定的多边形小于单个半球,则 MongoDB CRS 的$geoWithin行为与默认 CRS 相同。另请参阅“大型”多边形。

如果查询是否包含在由平面上的传统坐标对定义的形状中,请使用以下事务语法:

{
<location field>: {
$geoWithin: { <shape operator>: <coordinates> }
}
}

可用形状操作符包括:

重要

如果使用经度和纬度,请按照 longitude, latitude 的顺序指定坐标。

$geoWithin不需要地理空间索引。但是,地理空间索引可提高查询性能。 2 dsphere2 d地理空间索引都支持$geoWithin

$geoWithin操作符不返回排序结果。因此,MongoDB 返回$geoWithin查询的速度比对结果进行排序的地理空间$near$nearSphere查询更快。

$geoWithin 不保证它会考虑一个几何体来纳入其组件几何体,或另一个共享其组件几何体的多边形。

对于$geoWithin ,如果您指定面积大于单个半球的单环多边形,请在$geometry表达式中包含自定义 MongoDB 坐标参考系。否则, $geoWithin将查询互补几何体。对于面积大于半球的所有其他 GeoJSON 多边形, $geoWithin会查询互补几何体。

以下示例选择了完全存在于 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" }
}
}
}
}
}
)
$within

自版本 2.4 起已弃用$geoWithin 替换了MongoDB 2.4 中的 $within

← $geoIntersects
$near →

在此页面上