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

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

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

相关文章
相关标签/搜索