MongoDB 不專業指北(十四):搖一搖發現附近的人

前傳

做爲寂寞沙洲冷、單身比例高的程序猿人羣,少不得拿出手機搖一搖,看看附近有沒有鐘意的人。那這搖一搖過程當中發生了什麼?javascript

yaoyiyao.gif

毫無疑問,首先要獲取你本身的位置,而後再去拿你的位置取搜尋目標。java

6b369fa186e68be9542668d844ca1ae0.gif

2dsphere 球面位置索引

MongoDB 內置了2dsphere 球面索引,經過球面索引便可完成距離批量搜索。下面是測試數據:markdown

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] }}
 ]);
複製代碼

假設你此時孤身一人走在北京三里屯大街上,孑然一身,與那熱鬧非凡的夜生活顯得格格不入……測試

image.png

爲了打發這孤單寂寞的時光,你掏出了手機,準備搖一搖找我的來陪伴。忽然,一個聲音在你耳邊響起:「你須要先建立一個索引」。 沒錯!需有索引會更快速,程序猿講究的就是效率!,因而,你寫下了下面的指令:spa

db.location.createIndex({location: '2dsphere'});
複製代碼

「這還不夠,還須要往四周搜索一下,距離不要超過1千米!」3d

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

因而出現了你周圍潛在的目標,果真發現了三里屯附近的 MM!code

{
	"_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 這個神器,我神不知鬼不覺的就搜到了好多對象」。orm

「代碼裏的對象更多!」旁邊那個聲音又響起來了。對象

你猛地驚醒了過來,呆呆地看着電腦屏幕上的一個個對象,而三里屯距離你有幾千千米之遙——誰叫咱當時逃離北京了呢?索引

相關文章
相關標籤/搜索