Docs 菜单
Docs 主页
/ / /
Java Reactive Streams 驱动程序
/

地理空间Atlas Search

在此页面上

  • 先决条件
  • 连接到 MongoDB 部署
  • 创建2 dsphere 索引
  • 查询 GeoJSON 点附近的位置

为了支持地理空间查询,MongoDB 提供了地理空间索引和地理空间查询操作符。

要了解有关执行地理空间查询的更多信息,请参阅服务器手册中的地理空间查询

您必须设置以下组件才能运行本指南中的代码示例:

  • 一个test.restaurants 集合,其中填充了来自restaurants.json 文档资产Github 中 文件的文档。

  • 以下 import 语句:

import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoCollection;
import com.mongodb.reactivestreams.client.MongoDatabase;
import com.mongodb.client.model.geojson.*;
import com.mongodb.client.model.Indexes;
import com.mongodb.client.model.Filters;
import org.bson.Document;

重要

本指南使用Subscriber实现,如快速入门入门知识中所述。

首先,连接到 MongoDB 部署,然后声明并定义MongoDatabaseMongoCollection实例。

以下代码连接到在端口27017上的localhost上运行的独立 MongoDB 部署。 然后,定义database变量以引用test数据库,并collection变量以引用restaurants集合:

MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("restaurants");

要了解有关连接到 MongoDB 部署的更多信息,请参阅连接到 MongoDB教程。

要创建2dsphere索引,请使用Indexes.geo2dsphere()辅助程序为2dsphere索引创建规范。 将规范传递给MongoCollection.createIndex()方法以创建索引。

以下示例在restaurants集合中的"contact.location"字段上创建2dsphere索引:

MongoCollection<Document> collection = database.getCollection("restaurants");
collection.createIndex(Indexes.geo2dsphere("contact.location"))
.subscribe(new PrintSubscriber<String>());

MongoDB 提供各种地理空间查询操作符。为了便于创建地理空间查询筛选器,驱动程序提供了Filters类和com.mongodb.client.model.geojson包。

以下示例返回距离指定 GeoJSON Point实例至少1000米、最多5000米的文档,并按从最近到最远的顺序排序:

Point refPoint = new Point(new Position(-73.9667, 40.78));
collection.find(Filters.near("contact.location", refPoint, 5000.0, 1000.0))
.subscribe(new PrintDocumentSubscriber());

后退

文本搜索(Text Search)

来年

GridFS