AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

サンプル クエリの実行

Java Reactive Streams ドライバーは、次の 3 つのコンポーネントで構成される Reactive Streams API の実装です。

  • Publisher

  • Subscriber

  • Subscription

Publisherは、 SubscriberまたはSubscriberの複数のインスタンスから受信した要求に従って公開される、無制限の数のシーケンス要素のプロバイダーです。 Subscriptionは、 PublisherにサブスクライブするSubscriberの 1 対 1 のライフサイクルを表します。

Tip

Reactive Streams の詳細については、Reactive Streams のドキュメント を参照してください。

このチュートリアルでは、データベースをクエリするためにJava Reactive Streams Subscribersを実装する必要があります。 このガイドでは、Reactive Streams 仕様に基づいてJava Reactive Streams Subscribersを実装するライブラリである Reactive Streams ライブラリのメソッドを使用します。

React ライブラリの詳細については、 Project Reactive ドキュメントの使用開始を参照してください。

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 URI>"; // 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

<connection 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', ... }

Tip

エラーが発生した場合は、適切な 接続stringが指定されているかどうか、およびサンプルデータがロードされているかどうかを確認してください。

これらの手順を完了すると、ドライバーを使用してMongoDBデプロイに接続し、データベースをクエリし、結果を出力する動作アプリケーションが作成されます。

注意

この手順で問題が発生した場合は、このページの右側または右下にある Rate this pageタブを使用してフィードバックを送信してください。

MongoDB Stack Overflowタグ または MongoDB Reddit Community を使用して、一般的な質問のサポートを見つけることができます。

このページを評価