在MongoDB中,可以使用$geoNear
运算符和$geoWithin
运算符来进行距离范围查询。
- 使用
$geoNear
运算符进行距离排序和筛选:
db.collection.aggregate([ { $geoNear: { near: { type: "Point", coordinates: [longitude, latitude] }, // 经度和纬度 distanceField: "distance", // 距离字段 maxDistance: maxDistance, // 最大距离 query: { /* 其他查询条件 */ }, spherical: true // 使用球面几何计算距离 } } ])
- 使用
$geoWithin
运算符进行范围查询:
db.collection.find({ location: { $geoWithin: { $centerSphere: [ [longitude, latitude], // 经度和纬度 radius // 半径 ] } } })
请注意,使用上述方法进行距离范围查询时,需要确保在集合中的地理位置字段使用了地理索引。可以使用createIndex()
方法来创建地理索引。
更多关于MongoDB地理查询的信息,请参考官方文档:https://docs.mongodb.com/manual/geospatial-queries/