Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Java Reactive Streams 驱动程序
/

运行示例查询

Java Reactive Streams驾驶员是 Reactive Streams API的一个实施,它由三个组件组成:

  • Publisher

  • Subscriber

  • Subscription

Publisher是无限数量的有序元素的提供商,根据从其SubscriberSubscriber的多个实例收到的需求进行发布。 Subscription表示订阅PublisherSubscriber的一对一生命周期。

提示

To learn more about reactive streams, visit the Reactive Streams documentation.

在本教程中,您必须实现Java Reactive Streams Subscribers来查询数据库。 本指南使用 Reactor 库(一个基于响应式流规范的库)中的方法来实现Java响应式流Subscribers

To learn more about the Reactor library, see Getting Started in the Project Reactor documentation.

1

您必须使用集成开发环境 (IDE) 中的项目来完成以下步骤。 在您的项目中,在Java包中创建一个名为QueryDatabase的新Java文件。 将以下代码复制并粘贴到QueryDatabase文件:

import com.mongodb.*;
import com.mongodb.reactivestreams.client.MongoCollection;
import org.bson.Document;
import reactor.core.publisher.Mono;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoDatabase;
import static com.mongodb.client.model.Filters.eq;
public class QueryDatabase {
public static void main(String[] args) {
// Replace the placeholder with your Atlas connection string
String uri = "<connection string>";
// Construct a ServerApi instance using the ServerApi.builder() method
ServerApi serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.build();
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.serverApi(serverApi)
.build();
// Create a new client and connect to the server
try (MongoClient mongoClient = MongoClients.create(settings)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> movies = database.getCollection("movies");
Mono.from(movies.find(eq("title", "Back to the Future")))
.doOnSuccess(i -> System.out.println(i))
.doOnError(err -> System.out.println("Error: " + err.getMessage()))
.block();
}
}
}
2

将 占位符替换为您从本指南的 string<connection string>创建连接 中复制的连接字符串。string

3

在 IDE 或shell中运行应用程序。 输出显示您已连接到MongoDB并查询数据库。

{
_id: ...,
plot: 'A young man is accidentally sent 30 years into the past...',
genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ],
...
title: 'Back to the Future',
...
}

提示

如果遇到错误,请检查是否指定了正确的连接string ,以及是否加载了示例数据。

完成这些步骤后,您就拥有了一个正常运行的应用程序,它使用驾驶员连接到MongoDB 部署、查询数据库并打印结果。

注意

如果您在该步骤中遇到问题,请在 MongoDB 社区论坛中寻求帮助,或使用本页右侧或右下角的 Rate this page(本页内容评级)标签页提交反馈。

后退

创建连接字符串