

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

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

Amazon DocumentDB의 `$near` 연산자는 지정된 지점에 지리적으로 가까운 문서를 찾는 데 사용됩니다. 거리별로 정렬된 문서를 반환하고 가장 가까운 문서를 먼저 반환합니다. 이 연산자는 2dsphere 지리 공간 인덱스가 필요하며 위치 데이터에 대한 근접 쿼리에 유용합니다.

**파라미터**
+ `$geometry`: 근거리 쿼리의 중심점을 정의하는 GeoJSON Point 객체입니다.
+ `$maxDistance`: (선택 사항) 문서가 쿼리와 일치할 수 있는 지정된 지점으로부터 미터 단위의 최대 거리입니다.
+ `$minDistance`: (선택 사항) 문서가 쿼리와 일치할 수 있는 지정된 지점으로부터 미터 단위의 최소 거리입니다.

**인덱스 요구 사항**
+ `2dsphere index`: GeoJSON Point 데이터에 대한 지리 공간 쿼리에 필요합니다.

## 예제(MongoDB 쉘)
<a name="near-examples"></a>

다음 예제에서는 `$near` 연산자를 사용하여 워싱턴주 시애틀의 특정 위치에 가장 가까운 레스토랑을 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.usarestaurants.insert([
  {
    "name": "Noodle House",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.8,
    "location": { "type": "Point", "coordinates": [-122.3517, 47.6159] }
  },
  {
    "name": "Pike Place Grill",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.2,
    "location": { "type": "Point", "coordinates": [-122.3403, 47.6062] }
  },
  {
    "name": "Lola",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.5,
    "location": { "type": "Point", "coordinates": [-122.3407, 47.6107] }
  }
]);
```

**2Dsphere 인덱스 생성**

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

**GeoJSON Point를 사용한 쿼리 예제**

```
db.usarestaurants.find({
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $maxDistance: 100,
      $minDistance: 10
    }
  }
});
```

**출력**

```
{
  "_id" : ObjectId("69031ec9ea1c2922a1ce5f4a"),
  "name" : "Noodle House",
  "city" : "Seattle",
  "state" : "Washington",
  "rating" : 4.8,
  "location" : {
    "type" : "Point",
    "coordinates" : [ -122.3517, 47.6159 ]
  }
}
```

## 코드 예제
<a name="near-code"></a>

`$near` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

async function findNearbyRestaurants() {
  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 restaurants = db.collection('usarestaurants');

  // Create 2dsphere index
  await restaurants.createIndex({ "location": "2dsphere" });

  const result = await restaurants.find({
    location: {
      $near: {
        $geometry: {
          type: "Point",
          coordinates: [-122.3516, 47.6156]
        },
        $maxDistance: 100,
        $minDistance: 10
      }
    }
  }).toArray();

  console.log(result);

  client.close();
}

findNearbyRestaurants();
```

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

```
from pymongo import MongoClient

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

    # Create 2dsphere index
    restaurants.create_index([("location", "2dsphere")])

    result = list(restaurants.find({
        'location': {
            '$near': {
                '$geometry': {
                    'type': 'Point',
                    'coordinates': [-122.3516, 47.6156]
                },
                '$maxDistance': 100,
                '$minDistance': 10
            }
        }
    }))

    print(result)

    client.close()

find_nearby_restaurants()
```

------