mongodb的距离范围如何查询

1752
2023/8/14 23:47:08
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在MongoDB中,可以使用$geoNear运算符和$geoWithin运算符来进行距离范围查询。

  1. 使用$geoNear运算符进行距离排序和筛选:
db.collection.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [longitude, latitude] }, // 经度和纬度
distanceField: "distance", // 距离字段
maxDistance: maxDistance, // 最大距离
query: { /* 其他查询条件 */ },
spherical: true // 使用球面几何计算距离
}
}
])
  1. 使用$geoWithin运算符进行范围查询:
db.collection.find({
location: {
$geoWithin: {
$centerSphere: [
[longitude, latitude], // 经度和纬度
radius // 半径
]
}
}
})

请注意,使用上述方法进行距离范围查询时,需要确保在集合中的地理位置字段使用了地理索引。可以使用createIndex()方法来创建地理索引。

更多关于MongoDB地理查询的信息,请参考官方文档:https://docs.mongodb.com/manual/geospatial-queries/

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: mongodb怎么清空整张表数据