指定した多角形の境界内のロケーション データをクエリできます。
境界内の位置データをクエリするには、 $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を使用します。 次の$geoWithinクエリでは、4 つの冗長性を持つ多角形(直列)を指定し、その多角形内のポイントを返します。
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' } ]