面试题答案
一键面试- 步骤:
- 定义多边形区域:首先需要将给定的一系列经纬度点按照顺序组织成一个多边形的GeoJSON格式。在GeoJSON中,多边形由一个“type”字段(值为“Polygon”)和一个“coordinates”数组组成,“coordinates”数组的第一个元素是一个包含多边形顶点经纬度的数组,这些顶点需按顺时针或逆时针顺序排列。例如:
{ "type": "Polygon", "coordinates": [ [ [longitude1, latitude1], [longitude2, latitude2], [longitude3, latitude3], // 更多顶点... [longitude1, latitude1] // 闭合多边形,最后一个点与第一个点相同 ] ] }
- 确保数据正确存储:检查MongoDB集合中存储店铺位置信息的文档,位置字段需存储为GeoJSON格式。例如:
{ "storeName": "某店铺", "location": { "type": "Point", "coordinates": [longitude, latitude] } }
- 创建索引:为了提高查询性能,需要在存储店铺位置的字段上创建2dsphere索引。在MongoDB shell中,可以使用以下命令创建索引:
db.yourCollectionName.createIndex( { location: "2dsphere" } );
- 执行查询:使用
$geoIntersects
操作符进行查询,该操作符用于查找与指定几何形状相交的文档。在MongoDB shell中的查询示例如下:
var polygon = { "type": "Polygon", "coordinates": [ [ [longitude1, latitude1], [longitude2, latitude2], [longitude3, latitude3], // 更多顶点... [longitude1, latitude1] ] ] }; db.yourCollectionName.find({ location: { $geoIntersects: { $geometry: polygon } } });
- 相关操作符:
$geoIntersects
:用于查询与指定几何形状相交的文档,这里用于判断店铺位置(点)是否在多边形区域内。
- 索引使用:
- 2dsphere索引:适用于地理空间查询,特别是涉及球体表面(地球表面近似球体)上的点、线、多边形等几何形状的查询。在这种情况下,创建2dsphere索引能极大提升查询位于多边形区域内店铺的性能。它能高效处理球面几何计算,加速查询操作。