球体上の点近くのロケーションの検索
球上の指定した点の近くに表示されるロケーション データをクエリできます。
指定した点の近くの位置データをクエリするには、 $near
演算子を使用します。
db.<collection>.find( { <location field> : { $near : { $geometry : { type : "Point", coordinates : [ <longitude>, <latitude> ] }, $maxDistance : <distance in meters> } } } )
このタスクについて
経度と緯度の座標を指定する場合は、最初に経度、次に緯度を指定します。
有効な経度の値は、
-180
以上、180
以下です。有効な緯度の値は
-90
以上、90
以下です。
$maxDistance
フィールドに距離をメートル単位で指定します。
始める前に
これらのドキュメントを含む
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" } ] ) loc
フィールドの値はGeoJSON ポイントです。$near
演算子を使用して位置データをクエリするには、位置データを含む フィールドに地理空間インデックスを作成する必要があります。loc
フィールドに2 dsphere インデックスを作成します。db.places.createIndex( { "loc": "2dsphere" } )
手順
コレクションをクエリするには、 $near
を使用します。 次の$near
クエリは、 [ -73.92, 40.78 ]
にある GeoJSON ポイントから5000メートル以内にloc
フィールドを持つドキュメントを返します。
db.places.find( { loc: { $near: { $geometry: { type: "Point", coordinates: [ -73.92, 40.78 ] }, $maxDistance : 5000 } } } )
出力:
[ { _id: ObjectId("63f7c3b15e5eefbdfef81cab"), loc: { type: 'Point', coordinates: [ -73.88, 40.78 ] }, name: 'La Guardia Airport', category: 'Airport' }, { _id: ObjectId("63f7c3b15e5eefbdfef81caa"), loc: { type: 'Point', coordinates: [ -73.97, 40.77 ] }, name: 'Central Park', category: 'Park' } ]
結果は、クエリ点からの距離が最も近いものから最も遠いものの順にソートされます。