本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$near
Amazon DocumentDB 中的$near運算子用於尋找地理位置接近指定點的文件。它會傳回依距離排序的文件,以最接近的文件為先。此運算子需要 2dsphere 地理空間索引,對於位置資料的鄰近查詢非常有用。
參數
-
$geometry:GeoJSON 點物件,定義近查詢的中心點。 -
$maxDistance:(選用) 從指定點開始,文件可以符合查詢的最大距離,以公尺為單位。 -
$minDistance:(選用) 文件可以符合查詢之指定點的最小距離,以公尺為單位。
索引需求
-
2dsphere index:GeoJSON Point 資料上的地理空間查詢需要。
範例 (MongoDB Shell)
下列範例示範如何使用 $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 Point 查詢範例
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命令的程式碼範例,請選擇您要使用的語言標籤: