1. 程式人生 > >mongodb與lbs(一)查詢附近的點

mongodb與lbs(一)查詢附近的點

在移動端普及的今天,LBS應用需求也越來越大。比如查詢附近的人,最近的餐廳等。面對這些需求,MongoDB提供了功能完備的解決方案。下面通過一個案例講訴如何用mongoDB做位置搜尋。

這裡寫圖片描述
在這個圖片中,有A B C D E F G,假如我是搜尋點A。我想查詢離自己最近的點。下面是具體的操作步驟:
1.建立集合和索引。sp為建立索引的欄位名,我們建立的索引型別是2dsphere

 #建立2dsphere索引
 db.sphere.ensureIndex({"sp":"2dsphere"})

2.向集合中插入測試資料,我們插入的是實際的經緯度。
這裡需要注意的是,如果我們如果用的是2dsphere索引,那麼插入的應該是GeoJson資料。GeoJson的格式是
{ type: ‘GeoJSON type’ , coordinates: ‘coordinates’ }
其中type指的是型別,可以是Point(本例中用的),LineString,Polygon等,coordinates是一個座標陣列。英語好的同學可以去官網看看https://docs.mongodb.com/manual/reference/geojson/

#插入Point資料
db.sphere.insert({name:"A",sp:{type:"Point",coordinates:[105.754484701156,41.689607057699]}})
db.sphere.insert({name:"B",sp:{type:"Point",coordinates:[105.304045248031,41.783456183240]}})
db.sphere.insert({name:"C",sp:{type:"Point",coordinates:[105.084318685531,41.389027478812]}})
db.sphere.insert({name:"D",sp:{type:"Point",coordinates:[105.831388998031,41.285916385493]}})
db.sphere.insert({name:"E",sp:{type:"Point",coordinates:[106.128706502914,42.086868474465]}})
db.sphere.insert({name:"F",sp:{type:"Point",coordinates:[105.431074666976,42.009365053841]}})
db.sphere.insert({name:"G",sp:{type:"Point",coordinates:[104.705977010726,41.921549795110]}})

3.進行查詢。介紹一下其中的引數
(1)geoNear:我們要查詢的集合名稱
(2)near:就是基於那個點進行搜尋,這裡是我們的搜尋點A
(3)spherical:是個布林值,如果為true,表示將計算實際的物理距離比如兩點之間有多少km,若為false,則會基於點的單位進行計算
(4)minDistance:搜尋的最小距離,這裡的單位是米
(5)maxDistance:搜尋的最大距離

db.runCommand({
    geoNear:"sphere",
    near:{type:"Point",coordinates:[105.794621276855,41.869574065014]},
    spherical:true,
    minDistance:25000,
    maxDistance:40000,
    })

(4)結果分析

{
    "waitedMS" : NumberLong(0),
    "results" : [ 
        {
            "dis" : 33887.5416611258,
            "obj" : {
                "_id" : ObjectId("57e3857e6a4a326367ae0d05"),
                "name" : "F",
                "sp" : {
                    "type" : "Point",
                    "coordinates" : [ 
                        105.431074666976, 
                        42.009365053841
                    ]
                }
            }
        }, 
        {
            "dis" : 36734.9748784127,
            "obj" : {
                "_id" : ObjectId("57e3857e6a4a326367ae0d04"),
                "name" : "E",
                "sp" : {
                    "type" : "Point",
                    "coordinates" : [ 
                        106.128706502914, 
                        42.086868474465
                    ]
                }
            }
        }
    ],
    "stats" : {
        "nscanned" : 24,
        "objectsLoaded" : 20,
        "avgDistance" : 35311.2582697693,
        "maxDistance" : 36734.9748784127,
        "time" : 87
    },
    "ok" : 1.0
}

在results中,我們搜尋到了點F和E。每個文件都加上了一個dis欄位,他表示這個點離你搜索點的距離。比如說,在結果中name為F的點的dis為33887.5416611258。表示F點距離搜尋點的距離是33887米。這個結果對於LBS應用是非常有用的。
好了,今天就介紹到這裡。關於MongoDB的其他特性。我將持續更新。