

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# \$1geoNear
<a name="geoNear"></a>

`$geoNear` 集約ステージは、指定されたポイントに近接した順序でドキュメントを返します。ポイントからの距離を計算し、出力ドキュメントに距離を含めます。

**パラメータ**
+ `near`: GeoJSON またはレガシー座標として指定された距離を計算するポイント。
+ `distanceField`: 計算された距離を保存するフィールド名。
+ `spherical`: 球形ジオメトリを使用するかどうかを示すブール値 (GeoJSON ポイントに必要）。
+ `maxDistance`: オプション。中心点からの最大距離。
+ `minDistance`: オプション。中心点からの最小距離。
+ `query`: オプション。適用する追加のフィルター条件。
+ `limit`: オプション。返されるドキュメントの最大数。
+ `key`: オプション。複数の地理空間インデックスが存在する場合に地理空間クエリに使用するフィールド。

## 例 (MongoDB シェル)
<a name="geoNear-examples"></a>

次の例は、 `$geoNear`ステージを使用して、特定の場所に最も近いストアを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.stores.createIndex({ location: "2dsphere" });

db.stores.insertMany([
  { _id: 1, name: "Store A", location: { type: "Point", coordinates: [-122.4, 37.8] } },
  { _id: 2, name: "Store B", location: { type: "Point", coordinates: [-122.5, 37.7] } },
  { _id: 3, name: "Store C", location: { type: "Point", coordinates: [-122.3, 37.9] } }
]);
```

**クエリの例**

```
db.stores.aggregate([
  {
    $geoNear: {
      near: { type: "Point", coordinates: [-122.4, 37.8] },
      distanceField: "distance",
      spherical: true
    }
  }
]);
```

**出力**

```
[
  { _id: 1, name: 'Store A', location: { type: 'Point', coordinates: [ -122.4, 37.8 ] }, distance: 0 },
  { _id: 3, name: 'Store C', location: { type: 'Point', coordinates: [ -122.3, 37.9 ] }, distance: 13877.82 },
  { _id: 2, name: 'Store B', location: { type: 'Point', coordinates: [ -122.5, 37.7 ] }, distance: 15557.89 }
]
```

## コードの例
<a name="geoNear-code"></a>

`$geoNear` 集約ステージを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('stores');

  const result = await collection.aggregate([
    {
      $geoNear: {
        near: { type: "Point", coordinates: [-122.4, 37.8] },
        distanceField: "distance",
        spherical: true
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['stores']

    result = list(collection.aggregate([
        {
            '$geoNear': {
                'near': { 'type': 'Point', 'coordinates': [-122.4, 37.8] },
                'distanceField': 'distance',
                'spherical': True
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------