1、 MongoDB支持二维空间索引,这是设计时考虑到基于位置的查询。 如果需要使用这种索引,应确定对象中存储的字段是子对象或数组,前两个元素为X,Y坐标
2、插入数据
db.location.insert({"loc":[20,20]});
3、创建索引
db.location.ensuerIndex({"loc":"2d"});
4、$near查询
db.location.find({"loc":{$near:[20,20]}}).limit(10);
上面的一句将按离目标点(20,20)距离最近的10个点(距离倒序排列)
5、geoNear Command
虽然find()语法为查询的首选,Mongo也提供来了 geoNear 命令来执行相似的函数。geoNear命令有一个额外的好处是结果中返回距离目标点的距离,以及一些利于排除故障的信息。
db.runCommand({geoNear:"location",near:[20,20],num:2});
6、 Bounds Queries
$within 参数可以代替$near来查找一个形状之内结果。同时,也支持$box(矩形)和$center(圆环)
想要查找一个一个矩形之内所有的点,必须制定该矩形的左下角和右上角坐标:
box = [[10,10],[40,40]]
db.location.find({"loc":{$within:{"$box":box}}})
查询索引
> db.test.getIndexes()
删除索引的命令:
> db.test.dropIndex({"username":1})