地理空间查询
地理空间索引与位置查询
语法
db.collection.createIndex({ <locationField>: "2dsphere" })说明
MongoDB 支持 2dsphere(球面几何)和 2d(平面坐标)两种地理空间索引。配合 $near、$geoWithin、$geoNear、$geometry 等操作符,可高效查询位置附近或区域内文档。广泛用于 LBS、地图、配送等场景。
参数
2dsphere球面地理索引,支持 GeoJSON(推荐)
2d平面坐标索引(旧版,简单场景用)
$near查询离指定点最近的文档(需配合 2dsphere/2d)
$geoWithin查询在指定区域内的文档
$geoNear聚合管道中的地理空间查询阶段
$geometry指定 GeoJSON 几何对象(Point、Polygon 等)
$maxDistance限制 $near 查询的最大距离(米)
示例
创建 2dsphere 索引
在 location 字段上创建地理索引
db.stores.createIndex({ location: "2dsphere" })$near 附近查询
查找最近的 5 家商店
db.stores.find({ location: { $near: { $geometry: { type: "Point", coordinates: [121.5, 31.2] }, $maxDistance: 5000 } } }).limit(5)$geoWithin 区域内查询
查询在指定多边形内的门店
db.stores.find({ location: { $geoWithin: { $geometry: { type: "Polygon", coordinates: [[[121.3,31.0],[121.7,31.0],[121.7,31.4],[121.3,31.4],[121.3,31.0]]] } } } })$geoNear 聚合查询
聚合管道中计算距离
db.stores.aggregate([{ $geoNear: { near: { type: "Point", coordinates: [121.5, 31.2] }, distanceField: "distance", maxDistance: 3000, spherical: true } }])