$geoWithin(几何区域内)
最后更新:2026-10-09
$geoWithin(几何区域内)
$geoWithin 查询地理位置落在指定几何形状内的文档。支持 $box(矩形)、$polygon(多边形)、$center(圆,平面距离)、$centerSphere(球面圆)、$geometry(GeoJSON)。`{ loc: { $geoWithin: { $box: [[0, 0], [10, 10]] } } }`。包含边界点,需要 2dsphere 或 2d 索引。
| 分类 | 地理空间 |
|---|---|
| MongoDB 版本 | 2.4+ |
| 示例语言 | mongosh (Shell) |
📝 语法
{ <位置字段>: { $geoWithin: { $geometry: <GeoJSON> } } }
⚙️ 参数
| 位置字段 | 存储坐标的字段名。 |
|---|---|
| 几何形状 | $box、$polygon、$center、$centerSphere 或 $geometry。 |
返回值:匹配的文档游标
▶ 示例
请在本地安装的 mongosh 中执行以下命令(需已启动 mongod):
// $geoWithin:矩形区域内的门店
db.stores.find({
loc: { $geoWithin: { $box: [[-73.98, 40.75], [-73.97, 40.76]] } }
})
// GeoJSON 多边形
db.stores.find({
loc: { $geoWithin: { $geometry: { type: 'Polygon', coordinates: [[[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]] } } }
})
运行结果:
// 返回坐标落在矩形或多边形内的门店文档
📌 注意事项
- 必须建 2dsphere(GeoJSON)或 2d(传统坐标对)索引
- 包含边界上的点
- 结果不按距离排序,距离排序用 $near
🏷️ 相关标签
💡 相关案例
更多实战案例即将上线,敬请期待。
📚 相关教程
❓ 常见问题
Q$geoWithin 和 $near 有什么区别?
A$geoWithin 只判断「在区域内」,不排序;$near 按距离排序返回。
Q$geoWithin 支持圆形吗?
A支持,$center 画平面圆、$centerSphere 画球面圆。
Q$geoWithin 必须建索引吗?
A是,2dsphere 或 2d 索引是硬性要求。