MongoDB 地理空间查询
使用 GeoJSON 和地理索引实现位置查询。 · 难度:入门 · +15XP
地理空间数据
MongoDB 支持 GeoJSON 对象(Point, LineString, Polygon 等)并提供了 2dsphere 索引进行地理查询。
创建索引
db.places.createIndex({ location: '2dsphere' });插入地点
db.places.insertOne({
name: "中央公园",
location: { type: "Point", coordinates: [-73.9654, 40.7829] }
});查询附近位置
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [-73.97, 40.78] },
$maxDistance: 1000 // 米
}
}
});| 操作符 | 说明 |
|---|---|
| $near | 按距离排序返回最近点 |
| $geoWithin | 查找多边形内的点 |
| $geoIntersects | 查找与几何体相交的文档 |
练习提示
创建一个咖啡店集合,插入5个带有坐标的店铺,然后查询你当前位置1公里内的店铺。