GeoJSON オブジェクトと交差する位置データをクエリできます。 たとえば、パイプラインの座標を保存するアプリケーションを考えてみましょう。 ロード トリップを表す GeoJSON LineStringを作成し、ロード トリップ ルートと交差するスタンドアロン ステーションをクエリできます。
GeoJSON オブジェクトと交差する位置データをクエリするには、 $geoIntersects演算子を使用します。
db.<collection>.find( { <location field> : { $geoIntersects : { $geometry : { type : "<GeoJSON object type>", coordinates : [ <coordinates> ] } } } } )
このタスクについて
経度と緯度の座標を指定する場合は、最初に経度、次に緯度を指定します。
有効な経度の値は、
-180以上、180以下です。有効な緯度の値は
-90以上、90以下です。
指定されたオブジェクトと少なくとも 1 つの点を共有する場合、そのロケーションはオブジェクトと交差されます。 これには、共有エッジを持つオブジェクトが含まれます。
$geoIntersectsには地理空間インデックスは必要ありません。 ただし、地理空間インデックスを使用するとクエリのパフォーマンスが向上します。 2dsphere地理空間インデックスのみが$geoIntersectsをサポートします。 詳細については、 「2dsphere インデックスの作成」 を参照してください。
始める前に
これらのドキュメントを含むgasStationsコレクションを作成します。
db.gasStations.insertMany( [ { loc: { type: "Point", coordinates: [ -106.31, 35.65 ] }, state: "New Mexico", country: "United States", name: "Horizons Gas Station" }, { loc: { type: "Point", coordinates: [ -122.62, 40.75 ] }, state: "California", country: "United States", name: "Car and Truck Rest Area" }, { loc: { type: "Point", coordinates: [ -72.71, 44.15 ] }, state: "Vermont", country: "United States", name: "Ready Gas and Snacks" } ] )
手順
次の$geoIntersectsクエリでは、4 つのポイントを含むLineStringを指定し、 行と交差するドキュメントを返します。
db.gasStations.find( { loc: { $geoIntersects: { $geometry: { type: "LineString", coordinates: [ [ -105.82, 33.87 ], [ -106.01, 34.09 ], [ -106.31, 35.65 ], [ -107.39, 35.98 ] ] } } } } )
出力:
[ { _id: ObjectId("63f658d45e5eefbdfef81ca4"), loc: { type: 'Point', coordinates: [ -106.31, 35.65 ] }, state: 'New Mexico', country: 'United States', name: 'Horizons Gas Station' } ]