$nearSphere - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$nearSphere

Amazon DocumentDB の $nearSphere演算子は、地理空間ポイントから指定された距離内にあるドキュメントを検索するために使用されます。この演算子は、特定の場所の特定の半径内のすべてのレストランを検索するなど、地理空間クエリに特に役立ちます。

パラメータ

  • $geometry: 参照ポイントを表す GeoJSON オブジェクト。type フィールドと coordinatesフィールドを持つPointオブジェクトである必要があります。

  • $minDistance: (オプション) ドキュメントが置かなければならない参照ポイントからの最小距離 (メートル単位)。

  • $maxDistance: (オプション) ドキュメントが置かなければならない参照ポイントからの最大距離 (メートル単位)。

例 (MongoDB シェル)

この例では、ワシントン州シアトルの特定の場所から 2 キロメートル (2000 メートル) 以内にすべてのレストランがあります。

サンプルドキュメントを作成する

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

クエリの例

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

出力

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

コードの例

$nearSphere コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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