$geoIntersects - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$geoIntersects

Amazon DocumentDB 中的$geoIntersects運算子用於尋找地理空間資料與指定 GeoJSON 物件相交的文件。此運算子適用於需要根據文件與指定地理形狀的空間關係來識別文件的應用程式,例如多邊形或多邊形。

參數

  • $geometry:GeoJSON 物件,代表要檢查交集的形狀。支援的 GeoJSON 物件類型為 PointPolygonLineStringMultiPolygon

範例 (MongoDB Shell)

下列範例示範如何使用 $geoIntersects運算子來尋找 Amazon DocumentDB 中指定座標集的狀態名稱。

建立範例文件

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

查詢範例

var location = [-73.965355, 40.782865]; db.states.find({ "loc": { "$geoIntersects": { "$geometry": { "type": "Point", "coordinates": location } } } }, { "name": 1 });

輸出

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

程式碼範例

若要檢視使用 $geoIntersects命令的程式碼範例,請選擇您要使用的語言標籤:

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()