球上の指定した点の近くに表示されるロケーション データをクエリできます。
指定した点の近くの位置データをクエリするには、 $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' } ]
結果は、クエリ点からの距離が最も近いものから最も遠いものの順にソートされます。