跳至主要內容

Mongo-地理空间查询

Zenghr大约 2 分钟

Mongo-地理位置查询

MongoDB通过使用$near$withingeoWithin$nearSphere等运算符支持地理空间查询。Criteria类提供了特定于地理空间查询的方法。还有一些形状类(BoxCirclePoint)与地理空间相关的Criteria方法结合使用

演示类 Venue

@Document(collection="newyork")
public class Venue {

  @Id
  private String id;
  private String name;
  private double[] location;

  @PersistenceConstructor
  Venue(String name, double[] location) {
    super();
    this.name = name;
    this.location = location;
  }

  public Venue(String name, double x, double y) {
    super();
    this.name = name;
    this.location = new double[] { x, y };
  }

  public String getName() {
    return name;
  }

  public double[] getLocation() {
    return location;
  }

  @Override
  public String toString() {
    return "Venue [id=" + id + ", name=" + name + ", location="
        + Arrays.toString(location) + "]";
  }
}

Circle 查询

要查找Circle内的位置,您可以使用以下查询:

Circle circle = new Circle(-73.99171, 40.738868, 0.01);
List<Venue> venues =
    template.find(new Query(Criteria.where("location").within(circle)), Venue.class);

要使用球面坐标查找Circle内的场地,您可以使用以下查询:

Circle circle = new Circle(-73.99171, 40.738868, 0.003712240453784);
List<Venue> venues =
    template.find(new Query(Criteria.where("location").withinSphere(circle)), Venue.class);

Box 查询

要查找Box内的场地,您可以使用以下查询:

//lower-left then upper-right
Box box = new Box(new Point(-73.99756, 40.73083), new Point(-73.988135, 40.741404));
List<Venue> venues =
    template.find(new Query(Criteria.where("location").within(box)), Venue.class);

Point 查询

要查找Point附近的场地,您可以使用以下查询:

Point point = new Point(-73.99171, 40.738868);
List<Venue> venues =
    template.find(new Query(Criteria.where("location").near(point).maxDistance(0.01)), Venue.class);
Point point = new Point(-73.99171, 40.738868);
List<Venue> venues =
    template.find(new Query(Criteria.where("location").near(point).minDistance(0.01).maxDistance(100)), Venue.class);

要使用球面坐标查找Point附近的场地,您可以使用以下查询:

Point point = new Point(-73.99171, 40.738868);
List<Venue> venues =
    template.find(new Query(
        Criteria.where("location").nearSphere(point).maxDistance(0.003712240453784)),
        Venue.class);

地理附近查询

MongoDB支持在数据库中查询地理位置并同时计算与给定原点的距离。通过地理附近查询,您可以表达查询,例如“查找周围10英里内的所有餐馆”。为了让您这样做,MongoOperations提供了geoNear(…)方法,它们以NearQuery作为参数(以及已经熟悉的实体类型和集合),如以下示例所示:

Point location = new Point(-73.99171, 40.738868);
NearQuery query = NearQuery.near(location).maxDistance(new Distance(10, Metrics.MILES));
// mongoTemplate.geoNear()方法是专门查询地图附近集合的集成mongo的方法
GeoResults<Venue> = mongoTemplate.geoNear(query, Venue.class);

参考资料