MongoDB 报错:use geoNear command rather than $near query

    技术2022-07-10  92

     

    1.在mongodb的shard集群中,基于2dsphere,没法在find命令中使用:db.sz_user({loc:{$near:{……}}),这是mongodb的一个bug,会报错:use geoNear command rather than $near query,但是在非shard集群中是可以在find中使用$near。shard集群中使用runCommand是可以的,但是runCommand在高并发时,会停顿几秒,使用db.sz_user.aggregate($geoNear)能解决此问题。所以一句话,在shard集群中,$near没法用,runCommand高并发性能有问题,$geoNear才能完美解决此问题

    2.springboot+mongodb实现对指定经纬度

    mongo非集群:

    @Autowired //织入mongo模板连接 private MongoTemplate mongoTemplate; @Override public List<Bike> findNear(Bike bike) { //加入查询条件 bike.getLongitude() bike.getLatitude() 经度纬度 status 状态 Query query=new Query(); query.addCriteria(Criteria.where("status").is(bike.getStatus())) .addCriteria(Criteria.where("loc").near(new Point(bike.getLongitude(),bike.getLatitude()))) .limit(10); //Bike.class自己的封装类 , “bike”mongoDB的集合名 List<Bike> list=this.mongoTemplate.find(query, Bike.class, "bike"); //已经获取数据,根据自己的业务来写 for(Bike b:list){ b.setBid(b.getId()); b.setId(null); b.setLatitude(b.getLoc()[0]); b.setLongitude(b.getLoc()[1]); b.setLoc(null); } return list; }

    mongo集群要修改以上代码:

    @Override public List<Bike> findNear(Bike bike) { Point point = new Point( bike.getLongitude(),bike.getLatitude()); //.num()是设置查询返回的结果数量。如果大于5条就只返回5条。 //radius 单位为m,所以要转成km. NearQuery query = NearQuery .near(point) .maxDistance(new Distance(1000 / 1000, Metrics.KILOMETERS)) .num(10L); GeoResults<Bike> geoResults = mongoTemplate.geoNear(query, Bike.class, "bike"); List<GeoResult<Bike>> content = geoResults.getContent(); //如果想获取查询结果集是自己封装的数据。只需要在进行一次遍历 List<Bike> list=new ArrayList<Bike>(); for (GeoResult<Bike> geoResult: content) { Bike b = geoResult.getContent(); System.out.println("===="+b.toString()); b.setBid(b.getId()); b.setLatitude(b.getLoc()[1]); b.setLongitude(b.getLoc()[0]); list.add(b); } return list; }

    3.Command failed with error 17444: 'Legacy point is out of bounds for spherical query

      如果出现3这个错误就是地理位置写反了需要调整Point point = new Point( bike.getLongitude(),bike.getLatitude());

    再看看mongo中的loc 位置是否正确

    Processed: 0.015, SQL: 9