本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$geoNear
$geoNear 彙總階段會依接近指定點的順序傳回文件。它會計算與點的距離,並在輸出文件中包含距離。
參數
-
near:計算距離的點,指定為 GeoJSON 或舊版座標。 -
distanceField:存放計算距離的欄位名稱。 -
spherical:布林值,指出是否使用球形幾何 (GeoJSON 點需要)。 -
maxDistance:選用。與中心點的距離上限。 -
minDistance:選用。與中心點的最小距離。 -
query:選用。要套用的其他篩選條件。 -
limit:選用。要傳回的文件數量上限。 -
key:選用。當存在多個地理空間索引時,用於地理空間查詢的欄位。
範例 (MongoDB Shell)
下列範例示範如何使用 $geoNear階段尋找最接近指定位置的商店。
建立範例文件
db.stores.createIndex({ location: "2dsphere" }); db.stores.insertMany([ { _id: 1, name: "Store A", location: { type: "Point", coordinates: [-122.4, 37.8] } }, { _id: 2, name: "Store B", location: { type: "Point", coordinates: [-122.5, 37.7] } }, { _id: 3, name: "Store C", location: { type: "Point", coordinates: [-122.3, 37.9] } } ]);
查詢範例
db.stores.aggregate([ { $geoNear: { near: { type: "Point", coordinates: [-122.4, 37.8] }, distanceField: "distance", spherical: true } } ]);
輸出
[
{ _id: 1, name: 'Store A', location: { type: 'Point', coordinates: [ -122.4, 37.8 ] }, distance: 0 },
{ _id: 3, name: 'Store C', location: { type: 'Point', coordinates: [ -122.3, 37.9 ] }, distance: 13877.82 },
{ _id: 2, name: 'Store B', location: { type: 'Point', coordinates: [ -122.5, 37.7 ] }, distance: 15557.89 }
]
程式碼範例
若要檢視使用$geoNear彙總階段的程式碼範例,請選擇您要使用的語言標籤: