查询多边形内的位置
您可以查询指定多边形周长内的位置数据。
要查询周长内的位置数据,请使用 $geoWithin
操作符并指定多边形顶点的坐标:
db.<collection>.find( { <location field> : { $geoWithin : { $geometry : { type : "Polygon", coordinates : [ <coordinates> ] } } } } )
关于此任务
使用
$geoWithin
操作符查询的字段值必须采用 GeoJSON 格式。在您指定经度和纬度坐标时,请先列出经度,然后再列出纬度。
有效经度值介于
-180
和180
之间,两者均包括在内。有效纬度值介于
-90
和90
之间,两者均包括在内。
当您指定多边形
coordinates
时,数组中的第一个坐标和最后一个坐标必须相同。这将闭合多边形的边界。$geoWithin
不需要地理空间索引。 但是,地理空间索引可提高查询性能。 只有2dsphere地理空间索引支持$geoWithin
。 有关更多信息,请参阅创建 2dsphere 索引。
开始之前
创建一个 places
集合,其中包含以下文档:
db.places.insertMany( [ { loc: { type: "Point", coordinates: [ -73.97, 40.77 ] }, name: "Central Park", category : "Park" }, { loc: { type: "Point", coordinates: [ -73.88, 40.78 ] }, name: "La Guardia Airport", category: "Airport" }, { loc: { type: "Point", coordinates: [ -1.83, 51.18 ] }, name: "Stonehenge", category : "Monument" } ] )
步骤
使用$geoWithin
来查询collection。以下$geoWithin
查询指定一个具有四个顶点的多边形(一个矩形)并返回该多边形内的点:
db.places.find( { loc: { $geoWithin: { $geometry: { type: "Polygon", coordinates: [ [ [ -73.95, 40.80 ], [ -73.94, 40.79 ], [ -73.97, 40.76 ], [ -73.98, 40.76 ], [ -73.95, 40.80 ] ] ] } } } } )
输出:
[ { _id: ObjectId("63a4a8d67348ebdcd0a061f0"), loc: { type: 'Point', coordinates: [ -73.97, 40.77 ] }, name: 'Central Park', category: 'Park' } ]