Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

多角形に囲まれたロケーションのクエリ

指定した多角形の境界内のロケーション データをクエリできます。

境界内の位置データをクエリするには、 $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'
}
]

戻る

クエリ

項目一覧