

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# \$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()
```

------