AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

$nearSphere(クエリ述語演算子)

$nearSphere

Specifies a point for which a geospatial query returns the documents from nearest to farthest. MongoDB calculates distances for $nearSphere using spherical geometry.

$nearSphere には地理空間インデックスが必要です。

  • GeoJSON ポイントとして定義されたロケーション データの2dsphereインデックス

  • legacy coordinate pairs として定義されたロケーション データの2dインデックス GeoJSON ポイント2dインデックスを使用するには、GeoJSON オブジェクトのcoordinatesフィールドにインデックスを作成します。

The $nearSphere operator can specify either a GeoJSON point or legacy coordinate point.

GeoJSONポイントを指定するには、次の構文を使用します。

{
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ <longitude>, <latitude> ]
},
$minDistance: <distance in meters>,
$maxDistance: <distance in meters>
}
}
  • 任意$minDistanceを使用すると、中心点から指定された 以上 の距離にあるドキュメントに結果が制限されます。

  • 任意$maxDistanceはどちらのインデックスでも使用できます。

レガシー座標を使用して点を指定するには、次の構文を使用します。

{
$nearSphere: [ <x>, <y> ],
$minDistance: <distance in radians>,
$maxDistance: <distance in radians>
}
  • オプション$minDistanceは、クエリが2dsphereインデックスを使用する場合にのみ使用できます。 $minDistanceでは、中心点から指定された 以上 の距離にあるドキュメントに結果が制限されます。

  • 任意$maxDistanceはどちらのインデックスでも使用できます。

レガシー座標に経度と緯度を使用する場合は、最初に経度、次に緯度を指定します。

You cannot combine the $nearSphere operator, which requires a special geospatial index, with a query operator or command that requires another special index. For example you cannot combine $nearSphere with the $text query.

The $nearSphere operator sorts documents by distance.

  • クエリで sort() メソッドを使用すると、MongoDB は 2 番目の並べ替え操作を実行して、一致するドキュメントの順序を変更します。大規模なコレクションをクエリする場合、これはクエリのパフォーマンスに悪影響を与える可能性があります。

  • ドキュメントの順序が重要でない場合は、並べ替えられていない結果が返されるため、代わりに $geoWithin 演算子の使用を検討してください。

  • $nearSphere はマッチ式演算子であり、集計パイプラインでは許可されていません。

MongoDB8.0 以降、$near 、 、$nearSphere は、指定された$geoNear GeoJSON ポイントのタイプがPoint であることを検証します。その他の入力型はエラーを返します。

locationフィールドと2dsphereインデックスを持つドキュメントを含むコレクションplacesについて考えます。

次に、次の例では、指定された点から少なくとも1000メートル、最大5000メートル離れたlocationを、最も近いものから最も遠いものの順に返します。

db.places.find(
{
location: {
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ -73.9667, 40.78 ]
},
$minDistance: 1000,
$maxDistance: 5000
}
}
}
)

locationフィールドに legacy coordinates pairs を持つドキュメントを含み、 2dインデックスを持つコレクションlegacyPlacesについて考えてみましょう。

次に、次の例では、 locationが指定された点から最大0.10ラジアンであるドキュメントを、最も近いものから最も遠いものの順に返します。

db.legacyPlaces.find(
{ location : { $nearSphere : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }
)

代わりに、コレクションに2dsphereインデックスがある場合は、オプションの$minDistance仕様を指定することもできます。 たとえば、次の例では、 locationが指定された点から少なくとも0.0004ラジアンであるドキュメントを、最も近いものから最も遠いものの順に返します。

db.legacyPlaces.find(
{ location : { $nearSphere : [ -73.9667, 40.78 ], $minDistance: 0.0004 } }
)
このページを評価

項目一覧