$near - Amazon DocumentDB

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

$near

Amazon DocumentDB の $near演算子は、指定されたポイントに地理的に近いドキュメントを検索するために使用されます。距離順に並べられたドキュメントが返され、最も近いドキュメントが最初に返されます。この演算子には 2 次元地理空間インデックスが必要で、位置データの近接クエリに役立ちます。

パラメータ

  • $geometry: ニアクエリの中心点を定義する GeoJSON ポイントオブジェクト。

  • $maxDistance: (オプション) ドキュメントがクエリに一致するように指定ポイントからメートル単位の最大距離。

  • $minDistance: (オプション) ドキュメントがクエリに一致するように指定ポイントからメートル単位の最小距離。

インデックスの要件

  • 2dsphere index: GeoJSON ポイントデータの地理空間クエリに必要です。

例 (MongoDB シェル)

次の例は、 $near演算子を使用して、ワシントン州シアトルの特定の場所に最も近いレストランを見つける方法を示しています。

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

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

2dsphere インデックスを作成する

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

GeoJSON ポイントを使用したクエリの例

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

出力

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

コードの例

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

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