Mongodb的2d查询

初始化两条有坐标的数据:
这里写图片描述
注意:location不能存储字符串。
为location这个字段添加2d索引:

 db.location.ensureIndex({"location":"2d"})

查询指定的一个点距离最近的100个点:

Point point = new Point(10,10);
List<HashMap> result = mongoTemplate.find(new Query(Criteria.where("location").near(point))
        ,HashMap.class,"location");

查询结果会按照距离进行排序,默认查询100条,可以通过limit来限制查询的条数。

查询一个点指定半径内的所有点(效率高于near):

Point point = new Point(10,10);
Circle circle = new Circle(point, 20);
List<HashMap> result = mongoTemplate.find(new Query(Criteria.where("location").within(circle))
        ,HashMap.class,"location");

计算球体距离范围内的点:

Point point = new Point(10,10);
Circle circle = new Circle(point, 1);
List<HashMap> result = mongoTemplate.find(new Query(Criteria.where("location").withinSphere(circle))
        ,HashMap.class,"location");

矩形查询:

Point point1 = new Point(10,10);
Point point2 = new Point(20,20);
Box box = new Box(point1, point2);
List<HashMap> result = mongoTemplate.find(new Query(Criteria.where("location").within(box))
        ,HashMap.class,"location");

空间距离查询:

Point point = new Point(10,10);
List<HashMap> result = mongoTemplate.find(new Query(Criteria.where("location").nearSphere(point).maxDistance(100))
        ,HashMap.class,"location");

以上的查询都只是图形查询,并非正在的gps之间的距离,例如[10,11]和[10,12]之间的距离只是1,并非经纬度对应的距离差,如果要查询对应的距离差,需要指定Distance对象的单位:

Point location = new Point(12, 12);
NearQuery query = NearQuery.near(location).maxDistance(new Distance(100000, Metrics.KILOMETERS));
GeoResults<HashMap> result = mongoTemplate.geoNear(query, HashMap.class,"location");

这种方式的查询,会返回真实的距离以及所有满足条件的平均距离。
within也可以指定查询的distance对象:

Point point = new Point(10,10);
Circle circle = new Circle(point, new Distance(1000));
List<HashMap> result = mongoTemplate.find(new Query(Criteria.where("location").near(point).maxDistance(10))
    ,HashMap.class,"location");

当然是用geoNear这种方法有一个好处,就是可以返回具体的距离是多少。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值