

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Dati geospaziali
<a name="mongo-apis-geospatial-operators"></a>

Questa sezione fornisce informazioni dettagliate sugli operatori geospaziali supportati da Amazon DocumentDB.

**Topics**
+ [\$1geometry](geometry.md)
+ [\$1geoIntersects](geoIntersects.md)
+ [\$1geoWithin](geoWithin.md)
+ [\$1maxDistance](maxDistance.md)
+ [\$1minDistance](minDistance.md)
+ [\$1near](near.md)
+ [\$1nearSphere](nearSphere.md)

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

L'`$geometry`operatore in Amazon DocumentDB viene utilizzato per specificare un oggetto geometrico GeoJSON come parte di una query geospaziale. Questo operatore viene utilizzato insieme ad altri operatori di interrogazione geospaziali come e per eseguire query spaziali sui dati. `$geoWithin` `$geoIntersects`

In Amazon DocumentDB, l'`$geometry`operatore supporta i seguenti tipi di geometria GeoJSON:
+ Point (Punto)
+ LineString
+ Poligono
+ MultiPoint
+ MultiLineString
+ MultiPolygon
+ GeometryCollection

**Parametri**
+ `type`: Il tipo di oggetto geometrico GeoJSON, ad esempio, ecc. `Point` `Polygon`
+ `coordinates`: Un array di coordinate che rappresentano la geometria. La struttura dell'array di coordinate dipende dal tipo di geometria.

## Esempio (MongoDB Shell)
<a name="geometry-examples"></a>

L'esempio seguente dimostra come utilizzare l'`$geometry`operatore per eseguire una `$geoIntersects` query in Amazon DocumentDB.

**Crea documenti di esempio**

```
db.locations.insertMany([
  { 
    "_id": 1,
    "name": "Location 1",
    "location": { 
      "type": "Point",
      "coordinates": [-73.983253, 40.753941]
    }
  },
  { 
    "_id": 2,
    "name": "Location 2", 
    "location": {
      "type": "Polygon",
      "coordinates": [[
        [-73.998427, 40.730309],
        [-73.954348, 40.730309],
        [-73.954348, 40.780816],
        [-73.998427, 40.780816],
        [-73.998427, 40.730309]
      ]]
    }
  }
]);
```

**Esempio di interrogazione**

```
db.locations.find({
  "location": {
    "$geoIntersects": {
      "$geometry": {
        "type": "Polygon",
        "coordinates": [[
          [-73.998, 40.730],
          [-73.954, 40.730],
          [-73.954, 40.781],
          [-73.998, 40.781],
          [-73.998, 40.730]
        ]]
      }
    }
  }
})
```

**Output**

```
[
  {
    "_id": 2,
    "name": "Location 2",
    "location": {
      "type": "Polygon",
      "coordinates": [
        [
          [-73.998427, 40.730309],
          [-73.954348, 40.730309],
          [-73.954348, 40.780816],
          [-73.998427, 40.780816],
          [-73.998427, 40.730309]
        ]
      ]
    }
  }
]
```

## Esempi di codice
<a name="geometry-code"></a>

Per visualizzare un esempio di codice per l'utilizzo del `$geometry` comando, scegliete la scheda relativa alla lingua che desiderate utilizzare:

------
#### [ 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('locations');

  const query = {
    "location": {
      "$geoIntersects": {
        "$geometry": {
          "type": "Polygon",
          "coordinates": [[
            [-73.998, 40.730],
            [-73.954, 40.730],
            [-73.954, 40.781],
            [-73.998, 40.781],
            [-73.998, 40.730]
          ]]
        }
      }
    }
  };

  const result = await collection.find(query).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['locations']

    query = {
        "location": {
            "$geoIntersects": {
                "$geometry": {
                    "type": "Polygon",
                    "coordinates": [[
                        [-73.998, 40.730],
                        [-73.954, 40.730],
                        [-73.954, 40.781],
                        [-73.998, 40.781],
                        [-73.998, 40.730]
                    ]]
                }
            }
        }
    }

    result = list(collection.find(query))
    print(result)

    client.close()

example()
```

------

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

L'`$geoIntersects`operatore in Amazon DocumentDB viene utilizzato per trovare documenti i cui dati geospaziali si intersecano con un oggetto GeoJSON specificato. Questo operatore è utile per le applicazioni che richiedono l'identificazione dei documenti in base alla loro relazione spaziale con una determinata forma geografica, come un poligono o un multipoligono.

**Parametri**
+ `$geometry`: Un oggetto GeoJSON che rappresenta la forma da verificare per l'intersezione. I tipi di oggetti GeoJSON supportati `Point` sono`LineString`,, `Polygon` e. `MultiPolygon`

## Esempio (MongoDB Shell)
<a name="geoIntersects-examples"></a>

L'esempio seguente mostra come utilizzare l'`$geoIntersects`operatore per trovare il nome dello stato per un determinato set di coordinate in Amazon DocumentDB.

**Crea documenti di esempio**

```
db.states.insertMany([
  {
    "name": "New York",
    "loc": {
      "type": "Polygon",
      "coordinates": [[
        [-74.25909423828125, 40.47556838210948],
        [-73.70819091796875, 40.47556838210948],
        [-73.70819091796875, 41.31342607582222],
        [-74.25909423828125, 41.31342607582222],
        [-74.25909423828125, 40.47556838210948]
      ]]
    }
  },
  {
    "name": "California",
    "loc": {
      "type": "Polygon",
      "coordinates": [[
        [-124.4091796875, 32.56456771381587],
        [-114.5458984375, 32.56456771381587],
        [-114.5458984375, 42.00964153424558],
        [-124.4091796875, 42.00964153424558],
        [-124.4091796875, 32.56456771381587]
      ]]
    }
  }
]);
```

**Esempio di query**

```
var location = [-73.965355, 40.782865];

db.states.find({
  "loc": {
    "$geoIntersects": {
      "$geometry": {
        "type": "Point",
        "coordinates": location
      }
    }
  }
}, {
  "name": 1
});
```

**Output**

```
{ "_id" : ObjectId("536b0a143004b15885c91a2c"), "name" : "New York" }
```

## Esempi di codice
<a name="geoIntersects-code"></a>

Per visualizzare un esempio di codice per l'utilizzo del `$geoIntersects` comando, scegliete la scheda relativa alla lingua che desiderate utilizzare:

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

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

async function findStateByGeoIntersects(longitude, latitude) {
  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('states');

  const query = {
    loc: {
      $geoIntersects: {
        $geometry: {
          type: 'Point',
          coordinates: [longitude, latitude]
        }
      }
    }
  };

  const projection = {
    _id: 0,
    name: 1
  };

  const document = await collection.findOne(query, { projection });

  await client.close();
  
  if (document) {
    return document.name;
  } else {
    throw new Error('The geo location you entered was not found in the United States!');
  }
}
```

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

```
from pymongo import MongoClient

def find_state_by_geointersects(longitude, latitude):
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
        db = client.test
        collection_states = db.states

        query_geointersects = {
            "loc": {
                "$geoIntersects": {
                    "$geometry": {
                        "type": "Point",
                        "coordinates": [longitude, latitude]
                    }
                }
            }
        }

        document = collection_states.find_one(query_geointersects,
                                              projection={
                                                  "_id": 0,
                                                  "name": 1
                                              })
        if document is not None:
            state_name = document['name']
            return state_name
        else:
            raise Exception("The geo location you entered was not found in the United States!")
    except Exception as e:
        print('Exception in geoIntersects: {}'.format(e))
        raise
    finally:
        if client is not None:
            client.close()
```

------

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

L'`$geoWithin`operatore in Amazon DocumentDB viene utilizzato per trovare documenti i cui dati di posizione (rappresentati come oggetti GeoJSON) sono completamente contenuti all'interno di una forma specificata, come un poligono o un multipoligono. Ciò è utile per eseguire query su oggetti che si trovano all'interno di una regione geografica specifica.

**Parametri**
+ `$geometry`: Un oggetto GeoJSON che rappresenta la forma su cui eseguire la query.

## Esempio (MongoDB Shell)
<a name="geoWithin-examples"></a>

L'esempio seguente mostra come utilizzare l'`$geoWithin`operatore per trovare tutti gli aeroporti situati nello stato di New York.

**Crea documenti di esempio**

```
// Insert state document
db.states.insert({
    "name": "New York",
    "loc": {
        "type": "Polygon",
        "coordinates": [[
            [-79.76278, 45.0],
            [-73.94, 45.0],
            [-73.94, 40.5],
            [-79.76278, 40.5],
            [-79.76278, 45.0]
        ]]
    }
});

// Insert airport documents
db.airports.insert([
    {
        "name": "John F. Kennedy International Airport",
        "type": "airport",
        "code": "JFK",
        "loc": {
            "type": "Point",
            "coordinates": [-73.7781, 40.6413]
        }
    },
    {
        "name": "LaGuardia Airport",
        "type": "airport",
        "code": "LGA",
        "loc": {
            "type": "Point",
            "coordinates": [-73.8772, 40.7769]
        }
    },
    {
        "name": "Buffalo Niagara International Airport",
        "type": "airport",
        "code": "BUF",
        "loc": {
            "type": "Point",
            "coordinates": [-78.7322, 42.9403]
        }
    }
]);
```

**Esempio di interrogazione**

```
var state = db.states.findOne({"name": "New York"});

db.airports.find({
    "loc": {
        "$geoWithin": {
            "$geometry": state.loc
        }
    }
}, {
    "name": 1,
    "type": 1,
    "code": 1,
    "_id": 0
});
```

**Output**

```
[
  {
    "name": "John F. Kennedy International Airport",
    "type": "airport",
    "code": "JFK"
  },
  {
    "name": "LaGuardia Airport",
    "type": "airport",
    "code": "LGA"
  }
]
```

## Esempi di codice
<a name="geoWithin-code"></a>

Per visualizzare un esempio di codice per l'utilizzo del `$geoWithin` comando, scegliete la scheda relativa alla lingua che desiderate utilizzare:

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

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

async function findAirportsWithinState(stateName) {
  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 stateDoc = await db.collection('states').findOne({ name: stateName }, { projection: { _id: 0, loc: 1 } });
  const airportDocs = await db.collection('airports').find({
    loc: {
      $geoWithin: {
        $geometry: stateDoc.loc
      }
    }
  }, { projection: { name: 1, type: 1, code: 1, _id: 0 } }).toArray();

  console.log(airportDocs);

  await client.close();
}

findAirportsWithinState('New York');
```

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

```
from pymongo import MongoClient

def find_airports_within_state(state_name):
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
        db = client['test']
        state_doc = db.states.find_one({'name': state_name}, {'_id': 0, 'loc': 1})
        airport_docs = db.airports.find({
            'loc': {
                '$geoWithin': {
                    '$geometry': state_doc['loc']
                }
            }
        }, {'name': 1, 'type': 1, 'code': 1, '_id': 0})
        
        return list(airport_docs)
    except Exception as e:
        print(f'Error: {e}')
    finally:
        client.close()

airports = find_airports_within_state('New York')
print(airports)
```

------

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

L'`$maxDistance`operatore in Amazon DocumentDB viene utilizzato per specificare la distanza massima (in metri) da un punto GeoJSON entro cui i documenti devono trovarsi per essere inclusi nei risultati della query. Questo operatore viene utilizzato insieme all'operatore per eseguire interrogazioni `$nearSphere` geospaziali.

**Parametri**
+ `$maxDistance`: La distanza massima (in metri) dal punto di riferimento entro il quale i documenti devono trovarsi per essere inclusi nei risultati dell'interrogazione.

## Esempio (MongoDB Shell)
<a name="maxDistance-examples"></a>

L'esempio seguente mostra come utilizzare l'`$maxDistance`operatore in Amazon DocumentDB per trovare tutte le capitali degli stati entro 100 chilometri da Boston.

**Crea documenti di esempio**

```
db.capitals.insert([
  { state: "Massachusetts", city: "Boston", location: { type: "Point", coordinates: [-71.0589, 42.3601] } },
  { state: "Rhode Island", city: "Providence", location: { type: "Point", coordinates: [-71.4128, 41.8239] } },
  { state: "New Hampshire", city: "Concord", location: { type: "Point", coordinates: [-71.5383, 43.2067] } },
  { state: "Vermont", city: "Montpelier", location: { type: "Point", coordinates: [-72.5751, 44.2604] } }
]);
```

**Esempio di interrogazione**

```
db.capitals.find(
  {
    location: {
      $nearSphere: {
        $geometry: { type: "Point", coordinates: [-71.0589, 42.3601] },
        $maxDistance: 100000
      }
    }
  },
  { state: 1, city: 1, _id: 0 }
);
```

**Output**

```
[
  { "state": "Rhode Island", "city": "Providence" },
  { "state": "New Hampshire", "city": "Concord" }
]
```

## Esempi di codice
<a name="maxDistance-code"></a>

Per visualizzare un esempio di codice per l'utilizzo del `$maxDistance` comando, scegliete la scheda relativa alla lingua che desiderate utilizzare:

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

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

async function findCapitalsNearBoston() {
  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 capitals = db.collection('capitals');

  const result = await capitals.find({
    location: {
      $nearSphere: {
        $geometry: { type: "Point", coordinates: [-71.0589, 42.3601] },
        $maxDistance: 100000
      }
    }
  }, {
    projection: { state: 1, city: 1, _id: 0 }
  }).toArray();

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

findCapitalsNearBoston();
```

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

```
from pymongo import MongoClient

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

    result = list(capitals.find(
        {
            "location": {
                "$nearSphere": {
                    "$geometry": { "type": "Point", "coordinates": [-71.0589, 42.3601] },
                    "$maxDistance": 100000
                }
            }
        },
        {"state": 1, "city": 1, "_id": 0}
    ))

    print(result)
    client.close()

find_capitals_near_boston()
```

------

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

`$minDistance`è un operatore di ricerca utilizzato insieme `$nearSphere` o `$geoNear` per filtrare documenti che si trovano almeno alla distanza minima specificata dal punto centrale. Questo operatore è supportato in Amazon DocumentDB e funziona in modo simile alla sua controparte in MongoDB.

**Parametri**
+ `$minDistance`: La distanza minima (in metri) dal punto centrale per includere i documenti nei risultati.

## Esempio (MongoDB Shell)
<a name="minDistance-examples"></a>

In questo esempio, troveremo tutti i ristoranti entro un raggio di 2 chilometri da una località specifica a Seattle, Washington.

**Crea documenti di esempio**

```
db.usarestaurants.insertMany([
  {
    "state": "Washington",
    "city": "Seattle",
    "name": "Noodle House",
    "rating": 4.8,
    "location": {
      "type": "Point",
      "coordinates": [-122.3517, 47.6159]
    }
  },
  {
    "state": "Washington",
    "city": "Seattle",
    "name": "Pike Place Grill",
    "rating": 4.5,
    "location": {
      "type": "Point",
      "coordinates": [-122.3412, 47.6102]
    }
  },
  {
    "state": "Washington",
    "city": "Bellevue",
    "name": "The Burger Joint",
    "rating": 4.2,
    "location": {
      "type": "Point",
      "coordinates": [-122.2007, 47.6105]
    }
  }
]);
```

**Esempio di interrogazione**

```
db.usarestaurants.find({
  "location": {
    "$nearSphere": {
      "$geometry": {
        "type": "Point",
        "coordinates": [-122.3516, 47.6156]
      },
      "$minDistance": 1,
      "$maxDistance": 2000
    }
  }
}, {
  "name": 1
});
```

**Output**

```
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
```

## Esempi di codice
<a name="minDistance-code"></a>

Per visualizzare un esempio di codice per l'utilizzo del `$minDistance` comando, scegliete la scheda relativa alla lingua che desiderate utilizzare:

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

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

async function findRestaurantsNearby() {
  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('usarestaurants');

  const result = await collection.find({
    "location": {
      "$nearSphere": {
        "$geometry": {
          "type": "Point",
          "coordinates": [-122.3516, 47.6156]
        },
        "$minDistance": 1,
        "$maxDistance": 2000
      }
    }
  }, {
    "projection": { "name": 1 }
  }).toArray();

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

findRestaurantsNearby();
```

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

```
from pymongo import MongoClient

def find_restaurants_nearby():
    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.usarestaurants

    result = list(collection.find({
        "location": {
            "$nearSphere": {
                "$geometry": {
                    "type": "Point",
                    "coordinates": [-122.3516, 47.6156]
                },
                "$minDistance": 1,
                "$maxDistance": 2000
            }
        }
    }, {
        "projection": {"name": 1}
    }))

    print(result)
    client.close()

find_restaurants_nearby()
```

------

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

L'`$near`operatore in Amazon DocumentDB viene utilizzato per trovare documenti geograficamente vicini a un punto specifico. Restituisce i documenti ordinati in base alla distanza, con i documenti più vicini per primi. Questo operatore richiede un indice geospaziale a due sfere ed è utile per le interrogazioni di prossimità sui dati di localizzazione.

**Parametri**
+ `$geometry`: un oggetto GeoJSON Point che definisce il punto centrale per la query Near.
+ `$maxDistance`: (opzionale) La distanza massima in metri dal punto specificato che un documento può raggiungere per corrispondere alla query.
+ `$minDistance`: (opzionale) La distanza minima in metri dal punto specificato che un documento può raggiungere per corrispondere alla query.

**Requisiti dell'indice**
+ `2dsphere index`: necessario per le interrogazioni geospaziali sui dati GeoJSON Point.

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

L'esempio seguente mostra come utilizzare l'`$near`operatore per trovare i ristoranti più vicini a una località specifica a Seattle, Washington.

**Crea documenti di esempio**

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

**Crea un indice a due sfere**

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

**Esempio di query con GeoJSON Point**

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

**Output**

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

## Esempi di codice
<a name="near-code"></a>

Per visualizzare un esempio di codice per l'utilizzo del `$near` comando, scegli la scheda relativa alla lingua che desideri utilizzare:

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

------

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

L'`$nearSphere`operatore in Amazon DocumentDB viene utilizzato per trovare documenti che si trovano entro una distanza specificata da un punto geospaziale. Questo operatore è particolarmente utile per le interrogazioni geospaziali, ad esempio per trovare tutti i ristoranti entro un certo raggio da una determinata località.

**Parametri**
+ `$geometry`: un oggetto GeoJSON che rappresenta il punto di riferimento. Deve essere un `Point` oggetto con `type` e `coordinates` campi.
+ `$minDistance`: (opzionale) La distanza minima (in metri) dal punto di riferimento a cui devono essere i documenti.
+ `$maxDistance`: (opzionale) La distanza massima (in metri) dal punto di riferimento a cui devono essere i documenti.

## Esempio (MongoDB Shell)
<a name="nearSphere-examples"></a>

In questo esempio, troveremo tutti i ristoranti nel raggio di 2 chilometri (2000 metri) da una località specifica a Seattle, WA.

**Crea documenti di esempio**

```
db.usarestaurants.insert([
  {
    name: "Noodle House",
    location: { type: "Point", coordinates: [-122.3516, 47.6156] }
  },
  {
    name: "Pike Place Grill",
    location: { type: "Point", coordinates: [-122.3403, 47.6101] }
  },
  {
    name: "Seattle Coffee Co.",
    location: { type: "Point", coordinates: [-122.3339, 47.6062] }
  }
]);
```

**Esempio di interrogazione**

```
db.usarestaurants.find({
  location: {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $minDistance: 1,
      $maxDistance: 2000
    }
  }
}, {
  name: 1
});
```

**Output**

```
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
```

## Esempi di codice
<a name="nearSphere-code"></a>

Per visualizzare un esempio di codice per l'utilizzo del `$nearSphere` comando, scegliete la scheda relativa alla lingua che desiderate utilizzare:

------
#### [ 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');

  const result = await restaurants.find({
    location: {
      $nearSphere: {
        $geometry: {
          type: "Point",
          coordinates: [-122.3516, 47.6156]
        },
        $minDistance: 1,
        $maxDistance: 2000
      }
    }
  }, {
    projection: { name: 1 }
  }).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

    result = list(restaurants.find({
        'location': {
            '$nearSphere': {
                '$geometry': {
                    'type': 'Point',
                    'coordinates': [-122.3516, 47.6156]
                },
                '$minDistance': 1,
                '$maxDistance': 2000
            }
        }
    }, {
        'name': 1
    }))

    print(result)
    client.close()

find_nearby_restaurants()
```

------