MongoDB 不专业指北(十四):摇一摇发现附近的人

569 阅读2分钟

前传

作为寂寞沙洲冷、单身比例高的程序猿人群,少不得拿出手机摇一摇,看看附近有没有钟意的人。那这摇一摇过程中发生了什么?

yaoyiyao.gif

毫无疑问,首先要获取你自己的位置,然后再去拿你的位置取搜寻目标。

6b369fa186e68be9542668d844ca1ae0.gif

2dsphere 球面位置索引

MongoDB 内置了2dsphere 球面索引,通过球面索引即可完成距离批量搜索。下面是测试数据:

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

为了打发这孤单寂寞的时光,你掏出了手机,准备摇一摇找个人来陪伴。突然,一个声音在你耳边响起:“你需要先创建一个索引”。 没错!需有索引会更快速,程序猿讲究的就是效率!,于是,你写下了下面的指令:

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

“这还不够,还需要往四周搜索一下,距离不要超过1公里!”

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

于是出现了你周围潜在的目标,果然发现了三里屯附近的 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 这个神器,我神不知鬼不觉的就搜到了好多对象”。

“代码里的对象更多!”旁边那个声音又响起来了。

你猛地惊醒了过来,呆呆地看着电脑屏幕上的一个个对象,而三里屯距离你有几千公里之遥——谁叫咱当时逃离北京了呢?