$maxDistance - Amazon DocumentDB

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

$maxDistance

Amazon DocumentDB 中的$maxDistance運算子用於指定與 GeoJSON 點之間的最大距離 (以公尺為單位),文件必須位於其中才能包含在查詢結果中。此運算子會與運算$nearSphere子搭配使用,以執行地理空間查詢。

參數

  • $maxDistance:與文件必須位於 內的參考點之間的最大距離 (公尺),以包含在查詢結果中。

範例 (MongoDB Shell)

下列範例示範如何在 Amazon DocumentDB 中使用 $maxDistance運算子來尋找距離波士頓 100 公里內的所有州首字母。

建立範例文件

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

查詢範例

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

輸出

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

程式碼範例

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

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