

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

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

`$near`Operator di Amazon DocumentDB digunakan untuk menemukan dokumen yang secara geografis dekat titik tertentu. Ia mengembalikan dokumen yang dipesan berdasarkan jarak, dengan dokumen terdekat terlebih dahulu. Operator ini memerlukan indeks geospasial 2dsphere dan berguna untuk kueri kedekatan pada data lokasi.

**Parameter**
+ `$geometry`: Sebuah objek GeoJSON Point yang mendefinisikan titik pusat untuk query dekat.
+ `$maxDistance`: (opsional) Jarak maksimum dalam meter dari titik yang ditentukan bahwa dokumen dapat untuk mencocokkan kueri.
+ `$minDistance`: (opsional) Jarak minimum dalam meter dari titik yang ditentukan bahwa dokumen dapat untuk mencocokkan kueri.

**Persyaratan Indeks**
+ `2dsphere index`: Diperlukan untuk kueri geospasial pada data GeoJSON Point.

## Contoh (MongoDB Shell)
<a name="near-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$near` operator untuk menemukan restoran terdekat ke lokasi tertentu di Seattle, Washington.

**Buat dokumen sampel**

```
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] }
  }
]);
```

**Buat indeks 2dsphere**

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

**Contoh kueri dengan GeoJSON Point**

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

**Keluaran**

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

## Contoh kode
<a name="near-code"></a>

Untuk melihat contoh kode untuk menggunakan `$near` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

------