$geoNear(地理邻近)
最后更新:2026-10-09
$geoNear(地理邻近)
$geoNear 按地理位置从近到远输出文档,必须作为管道第一个阶段,并要求集合上有地理空间索引。它支持 distanceField 输出计算距离、spherical 球形或平面计算、minDistance 与 maxDistance 距离过滤,以及 key 指定使用哪个地理字段。输出文档会自动附带计算的距离。
| 分类 | 高级与诊断 |
|---|---|
| MongoDB 版本 | 1.0+ |
| 示例语言 | mongosh (Shell) |
📝 语法
{ $geoNear: { near: { type: "Point", coordinates: [ <经度>, <纬度> ] }, distanceField: "<距离字段>", spherical: <布尔>, maxDistance: <米>, query: <过滤条件> } }
⚙️ 参数
| near | 参考点,GeoJSON 点或旧式坐标数组。 |
|---|---|
| distanceField | 计算出的距离写入的字段名。 |
| spherical | 为 true 时按球形几何计算距离。 |
| query | 附加的查询过滤条件。 |
返回值:按距离升序的文档流(含 distanceField 距离字段)
▶ 示例
请在本地安装的 mongosh 中执行以下命令(需已启动 mongod):
// $geoNear:找 5 公里内的地点
db.places.aggregate([
{ $geoNear: {
near: { type: 'Point', coordinates: [-73.98, 40.75] },
distanceField: 'dist',
spherical: true,
maxDistance: 5000
} }
])
运行结果:
// 按距离升序,每条带 dist 字段
📌 注意事项
- 必须是管道第一个阶段
- 集合必须有地理空间索引(2dsphere 或 2d)
- near 为 GeoJSON 时必须 spherical: true
🏷️ 相关标签
💡 相关案例
📚 相关教程
❓ 常见问题
Q$geoNear 不建索引会怎样?
A报错,要求集合上存在 2dsphere 或 2d 地理索引。
Q能按距离过滤吗?
A能,用 maxDistance 和 minDistance,球形模式下单位为米。
Q还能加其他查询条件吗?
A能,用 query 参数,如 { query: { category: 'restaurant' } }。