1. 程式人生 > >MongoDB 學習筆記之 地理空間索引入門

MongoDB 學習筆記之 地理空間索引入門

geometry 分享 如果 sphere mce insert del sap 計劃

地理空間索引:

地理空間索引,可用於處理基於地理位置的查詢。

Point:用於指定所在的具體位置,我們以restaurants為例:

db.restaurants.insert({name: "Citi", loc: {type: "Point", coordinates: [52.37, 5.21]}})

db.restaurants.insert({name: "SAP", loc: {type: "Point", coordinates: [51.91, 4.41]}})

db.restaurants.insert({name: "IBM", loc: {type: "Point", coordinates: [52.36, 4.89]}})

技術分享

創建2dsphere索引:(經度默認範圍是-180到180,我們修改為-500到500)

db.restaurants.ensureIndex({loc: "2dsphere"},{min: -500, max: 500})

技術分享

搜索離指定地點最大距離在40000米之內的restaurants:

db.restaurants.find({loc: {$geoNear: {$geometry: {type: "Point", coordinates:[52.33,5.51]}, $maxDistance: 40000}}})

技術分享

查看執行計劃,發現使用了2dsphere索引:

db.restaurants.find({loc: {$geoNear: {$geometry: {type: "Point", coordinates:[52.33,5.51]}, $maxDistance: 40000}}}).explain(true)

技術分享

默認情況下,使用find()函數運行查詢足夠了,不過MongoDB還提供了geoNear函數,它還在查詢結果中提供了指定點到每個記錄的距離,以及一些額外的診斷信息。

db.runCommand({geoNear: "restaurants", near: {type: "Point", coordinates: [52.33, 5.51]}, spherical: true})

技術分享

地理空間類型和函數還有很多,但是和點的用法類似, 這裏不就一一舉例,如果大家在工作中使用它,可以到官網查詢。

MongoDB 學習筆記之 地理空間索引入門