MongoDB 如何實(shí)現(xiàn)搖一搖發(fā)現(xiàn)附近的人

前傳

作為寂寞沙洲冷、單身比例高的程序猿人群,少不得拿出手機(jī)搖一搖,看看附近有沒有鐘意的人。那這搖一搖過程中發(fā)生了什么?


搜索附近的人.gif

毫無疑問,首先要獲取你自己的位置,然后再去拿你的位置取搜尋目標(biāo)。

2dsphere 球面位置索引

MongoDB 內(nèi)置了2dsphere 球面索引,通過球面索引即可完成距離批量搜索。下面是測試數(shù)據(jù):

db.location.insert([
    {name: '三里屯MM1', gender: 'female', location: {type: 'Point', coordinates: [116.458347,39.940602] }},
    {name: '西直門GG1', gender: 'male', location: {type: 'Point', coordinates: [116.361446,39.946471] }},
    {name: '東直門MM2', gender: 'female', location: {type: 'Point', coordinates: [116.440967,39.945325] }},
    {name: '天安門MM3', gender: 'female', location: {type: 'Point', coordinates: [116.403963,39.915119] }},
    {name: '三里屯MM4', gender: 'female', location: {type: 'Point', coordinates: [116.460054,39.938063] }},
    {name: '三里屯MM5', gender: 'female', location: {type: 'Point', coordinates: [116.461082,39.944209] }},
    {name: '三里屯MM6', gender: 'female', location: {type: 'Point', coordinates: [116.461065,39.939399] }}
 ]);

假設(shè)你此時(shí)孤身一人走在北京三里屯大街上,形單影只,與那熱鬧非凡的夜生活顯得格格不入……

形單影只.jpg

為了打發(fā)這孤單寂寞的時(shí)光,你掏出了手機(jī),準(zhǔn)備搖一搖找個(gè)人來陪伴。突然,一個(gè)聲音在你耳邊響起:“你需要先創(chuàng)建一個(gè)索引”。
沒錯(cuò)!需有索引會更快速,程序猿講究的就是效率!,于是,你寫下了下面的指令:

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

“這還不夠,還需要往四周搜索一下,距離不要超過1公里!”

db.location.find(
  {
    location: {
      $near: {
        $geometry: {
          type: 'Point', coordinates: [116.459958,39.937193]
        }, 
        $maxDistance: 1000
      }
    }
  }
);

于是出現(xiàn)了你周圍潛在的目標(biāo),果然發(fā)現(xiàn)了三里屯附近的 MM!

{
    "_id" : ObjectId("60e459140d2f25c251fe0989"),
    "name" : "三里屯MM4",
    "gender" : "female",
    "location" : {
        "type" : "Point",
        "coordinates" : [
            116.460054,
            39.938063
        ]
    }
}
{
    "_id" : ObjectId("60e459140d2f25c251fe098b"),
    "name" : "三里屯MM6",
    "gender" : "female",
    "location" : {
        "type" : "Point",
        "coordinates" : [
            116.461065,
            39.939399
        ]
    }
}
{
    "_id" : ObjectId("60e459140d2f25c251fe0985"),
    "name" : "三里屯MM1",
    "gender" : "female",
    "location" : {
        "type" : "Point",
        "coordinates" : [
            116.458347,
            39.940602
        ]
    }
}
{
    "_id" : ObjectId("60e459140d2f25c251fe098a"),
    "name" : "三里屯MM5",
    "gender" : "female",
    "location" : {
        "type" : "Point",
        "coordinates" : [
            116.461082,
            39.944209
        ]
    }
}

你心里一陣竊喜,嘴里卻冷冷地說到:“誰說程序猿不好找對象的?有了 MongoDB 這個(gè)神器,我神不知鬼不覺的就搜到了好多對象”。

“代碼里的對象更多!”旁邊那個(gè)聲音又響起來了。

你猛地驚醒了過來,呆呆地看著電腦屏幕上的一個(gè)個(gè)對象,而三里屯距離你有幾千公里之遙——誰叫咱當(dāng)時(shí)逃離北京了呢?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容