定义
geoWithingeoWithin操作符支持查询给定几何图形内的地理点。 即使索引定义中的indexShapes值为true,也仅返回点。您可以在以下位置查询点:
圆形
边界框
多边形
指定要搜索的坐标时,必须先指定经度,然后指定纬度。 经度值可以介于
-180和180之间,两者均包括在内。 纬度值可以介于-90和90之间,两者均包括在内。 坐标值可以是整数或双精度值。注意
MongoDB Search 不支持以下内容:
非默认坐标参考系 (CRS)
平面 XY 坐标系(二维)
坐标对 点表示法(即
pointFieldName: [12, 34])
语法
geoWithin 通过以下语法实现:
{ "$search": { "index": <index name>, // optional, defaults to "default" "geoWithin": { "path": "<field-to-search>", "box | circle | geometry": <object>, "score": <score-options> } } }
选项
geoWithin 使用以下词条来构造查询:
字段 | 类型 | 说明 | 必要性 |
|---|---|---|---|
| 对象 | 指定搜索框左下角和右上角 GeoJSON 点的对象。该对象接受以下字段: 要了解如何在 GeoJSON 对象中指定 GeoJSON 数据,请参阅GeoJSON 对象。
| 视条件而定 |
| 对象 | 对象,用于指定Atlas Search的中心点和半径(以米为单位)。 该对象包含以下GeoJSON字段:
要了解如何在 GeoJSON 对象中指定 GeoJSON 数据,请参阅GeoJSON 对象。
| 视条件而定 |
| GeoJSON 对象 | GeoJSON对象,用于指定要在其中进行 的 MultiPolygon 或 Polygon Atlas Search。必须将多边形指定为闭环,其中最后一个位置与第一个位置相同。 When calculating geospatial results, MongoDB Search geoShape and geoWithin operators and MongoDB $geoIntersects operator use different geometries. This difference can be seen in how MongoDB Search and MongoDB draw polygonal edges. MongoDB Search 根据笛卡尔距离绘制多边形,笛卡尔距离是坐标参考系中两点之间的最短直线。 MongoDB draws polygons using the geodesic mode based on 2dsphere indexes that is built on top of a third-party library for geodesic types, or the flat mode, from 2d indexes. To learn more, see GeoJSON Objects. 对于涉及多边形的地理空间查询, MongoDB Search 和MongoDB可能会返回不同的结果。 要了解如何在 GeoJSON 对象中指定 GeoJSON 数据,请参阅GeoJSON 对象。
| 视条件而定 |
| 字符串或字符串数组 | 已索引的 geo 类型字段或要搜索的字段。 | 是 |
| 对象 | 分配给匹配搜索结果的分数。 默认情况下,结果中的分数为
有关在查询中使用 | no |
示例
The following examples use the listingsAndReviews collection in the sample_airbnb database. If you have the sample dataset on your cluster, you can create a custom MongoDB Search index for geo type and run the example queries on your cluster.
address.locationlistingsAndReviews使用以下示例索引定义为collection中的字段编制索引:
1 { 2 "mappings": { 3 "fields": { 4 "address": { 5 "fields": { 6 "location": { 7 "type": "geo" 8 } 9 }, 10 "type": "document" 11 }, 12 "property_type": { 13 "type": "token" 14 } 15 } 16 } 17 }
box 例子
以下查询使用geoWithin操作符和box字段在澳大利亚的边界框中搜索属性。
查询包括:
$limitstage to limit the output to3results.$projectstage to exclude all fields exceptnameandaddress.
注意
您无需在MongoDB Search查询中指定名为 default 的索引。如果索引有任何其他名称,则必须指定 index字段。
基本示例
元数据示例
circle 例子
以下查询使用geoWithin操作符和circle字段搜索加拿大指定坐标一英里半径范围内的房产。
查询包括:
$limitstage to limit the output to3results.$projectstage to exclude all fields exceptnameandaddress, and for Compass examples, the required steps reference.
注意
您无需在MongoDB Search查询中指定名为 default 的索引。如果索引有任何其他名称,则必须指定 index字段。
geometry 示例
以下示例使用 geoWithin 操作符和 geometry 字段搜索夏威夷州的房产。type 字段指定区域是 GeoJSON 多边形还是多边形集合。
注意
您无需在MongoDB Search查询中指定名为 default 的索引。如果索引有任何其他名称,则必须指定 index字段。