本文共 2345 字,大约阅读时间需要 7 分钟。
MongoDB 提供了丰富的地理搜索功能,能够支持复杂的地理查询场景。以下将详细介绍 MongoDB 的地理搜索操作符及其使用方法。
$geoWithin 用于查询多边形范围内的点,替代了已被废弃的 $within 查询。通过该操作符,可以高效地筛选位于特定多边形范围内的文档。
示例:
db.places.find({ loc: { $geoWithin: { $geometry: { type: "Polygon", coordinates: [ [ [0, 0], [3, 6], [6, 1], [0, 0] ] ] } } }}) 对于涉及大于单个半球的查询,需要添加 CRs(坐标参考系统)参数。CRs 参数用于指定坐标系,确保查询结果的精度。
示例:
db.places.find({ loc: { $geoWithin: { $geometry: { type: "Polygon", coordinates: [ [ [-100, 60], [-100, 0], [-100, -60], [100, -60], [100, 60], [-100, 60] ], ], crs: { type: "name", properties: { name: "urn:x-mongodb:crs:strictwinding:EPSG:4326" } } } } }}) $geoIntersects 用于查询几何对象与给定几何对象的交集。该操作符适用于需要判断文档是否与其他几何对象有交集的情况。
示例:
db.places.find({ loc: { $geoIntersects: { $geometry: { type: "Polygon", coordinates: [ [0, 0], [3, 6], [6, 1], [0, 0] ] } } }}) $near 用于返回与给定点距离在指定范围内的文档。该操作符适用于需要查找附近位置的场景。
示例:
db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] }, $minDistance: 1000, $maxDistance: 5000 } }}) $nearSphere 用于在球体上执行近似查询。该操作符适用于需要查找球体表面附近位置的场景。
示例:
db.places.find({ location: { $nearSphere: { $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] }, $minDistance: 1000, $maxDistance: 5000 } }}) 为了确保地理查询的高效性,必须在执行地理查询操作符之前创建相应的空间索引。以下是创建常用索引的示例:
示例:
db.places.ensureIndex({ loc: "2d"}) $center 查询用于查找位于指定圆心的文档。
示例:
db.places.find({ loc: { $geoWithin: { $center: [ [ -74, 40.74 ], 10 ] } }}) $centerSphere 查询用于球体表面查找。
示例:
db.places.find({ loc: { $geoWithin: { $centerSphere: [ [ -88, 30 ], 10/3963.2 ] } }}) $box 查询用于查找位于矩形区域的文档。
示例:
db.places.find({ loc: { $geoWithin: { $box: [ [0, 0], [100, 100] ] } }}) $polygon 查询用于查找位于多边形区域的文档。
示例:
db.places.find({ loc: { $geoWithin: { $polygon: [ [0, 0], [3, 6], [6, 0] ] } }}) 创建空间索引是使用 MongoDB 地理查询功能的前提条件。以下是创建常见索引的示例:
示例:
db.places.createIndex({ loc: "2d"}) 通过以上方法,您可以充分利用 MongoDB 的地理搜索功能,高效地执行复杂的地理查询任务。
转载地址:http://ujffk.baihongyu.com/