$geoIntersects(几何相交)
最后更新:2026-10-09
$geoIntersects(几何相交)
$geoIntersects 查询与指定 GeoJSON 几何形状相交的文档。`{ loc: { $geoIntersects: { $geometry: { type: 'Polygon', coordinates: [...] } } } }`。与 $geoWithin 的区别:$geoWithin 判断点是否在区域内,$geoIntersects 判断两个几何对象(点、线、面)是否相交。需要 2dsphere 索引。
| 分类 | 地理空间 |
|---|---|
| MongoDB 版本 | 2.4+ |
| 示例语言 | mongosh (Shell) |
📝 语法
{ <位置字段>: { $geoIntersects: { $geometry: <GeoJSON几何> } } }
⚙️ 参数
| 位置字段 | 存储坐标的字段名。 |
|---|---|
| GeoJSON几何 | Point、LineString、Polygon 等几何对象。 |
返回值:匹配的文档游标
▶ 示例
请在本地安装的 mongosh 中执行以下命令(需已启动 mongod):
// $geoIntersects:与给定路线相交的站点
// 需要 2dsphere 索引
db.stops.find({
loc: { $geoIntersects: {
$geometry: { type: 'LineString', coordinates: [[0, 0], [1, 1]] }
} }
})
运行结果:
// 返回与指定 LineString 相交(点在线段上等)的站点
📌 注意事项
- 与 $geoWithin 不同,支持线与面、面与面等相交判断
- 需要 2dsphere 索引,坐标必须为 GeoJSON 格式
- 结果不排序
🏷️ 相关标签
💡 相关案例
更多实战案例即将上线,敬请期待。
📚 相关教程
❓ 常见问题
Q$geoIntersects 和 $geoWithin 什么关系?
A$geoWithin 是「点在形状内」,$geoIntersects 是「几何相交」,范围更广。
Q能查点在多边形边界上吗?
A能,$geoIntersects 把边界视为相交。
Q$geoIntersects 需要什么索引?
A2dsphere 索引。