运算符 $geoIntersects
选择其位置字段与指定 GeoJSON 对象相交的文档。 如果要查找与特定地理区域相交的商店,此运算符非常有用。
语法
$geoIntersects
运算符的语法如下所示:
{
<location field>: {
$geoIntersects: {
$geometry: {
type: <GeoJSON type>,
coordinates: <coordinates>
}
}
}
}
参数
参数 | 说明 |
---|---|
location field |
包含 GeoJSON 对象的字段 |
type |
GeoJSON 对象类型(例如“Polygon”、“MultiPolygon”) |
coordinates |
定义 GeoJSON 对象的坐标 |
示例:
为了获得更好的性能,请先创建所需的 2dsphere 索引。
db.stores.createIndex({ "location": "2dsphere" })
现在,让我们找到使用集合与特定多边形区域相交的 stores
存储。 此多边形包含数据集中的多个存储位置。
db.stores.find({
'location': {
$geoIntersects: {
$geometry: {
type: "Polygon",
coordinates: [[
[-80.0, -75.0], // Bottom-left
[-80.0, -70.0], // Top-left
[-55.0, -70.0], // Top-right
[-55.0, -75.0], // Bottom-right
[-80.0, -75.0] // Close polygon
]]
}
}
}
}, {
"name": 1,
"location": 1
}).limit(2)
此查询返回存储,其位置与坐标定义的多边形轮廓相交。
{
"_id": "6bba7117-d180-4584-b50c-a2f843e9c9ab",
"name": "Wide World Importers | Craft Supply Mart - Heaneybury",
"location": { "lat": -64.4843, "lon": -107.7003 },
"city": "Heaneybury"
},
{
"_id": "2fd37663-e0ff-41d0-9c5a-3aec86285daa",
"name": "Relecloud | Cleaning Supply Closet - Patiencehaven",
"location": { "lat": -70.6077, "lon": -105.9901 },
"city": "Patiencehaven"
}
运算符适用于用例,例如
- 查找特定地理边界内的存储
- 标识服务覆盖范围区域
- 规划传递路由