Overview
このガイドでは、接続string とMongoClient {0 オブジェクトを使用して、さまざまなタイプのMongoDB 配置に接続する方法を説明します。
Atlas
MongoDBAtlas上の 配置に接続するには、 接続string に次の要素を含めます。
Atlas クラスターの URL
MongoDB ユーザー名
MongoDB パスワード
次に、接続stringを create() メソッドに渡して、MongoClientオブジェクトを構築します。
Tip
接続 Atlasを取得するには、 ドライバー接続ガイドstring に従ってください。
Atlas に接続するときは、Atlas がMongoDB Serverの新しいバージョンにアップグレードするときに重大な変更を回避するために、 Stable APIクライアントオプションを使用することをお勧めします。 Stable API機能の詳細については、 MongoDB Serverマニュアルの「 Stable API 」を参照してください。
次のコードは、 Java Reactive Streams ドライバーを使用して Atlas クラスターに接続する方法を示しています。 このコードでは、Stable APIバージョンを指定するためにserverApiオプションを使用します。
重要
React ライブラリ メソッド
このガイドでは、Reactive Streams 仕様に基づくライブラリである React ライブラリのメソッドを使用します。React をインストールするには、プロジェクト React ドキュメントの「 React の取得 」を参照してください。
import com.mongodb.ConnectionString; import com.mongodb.MongoClientSettings; import com.mongodb.ServerApi; import com.mongodb.ServerApiVersion; import org.bson.BsonDocument; import org.bson.BsonInt64; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoDatabase; import org.bson.conversions.Bson; import reactor.core.publisher.Mono; public class testing { 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("<database name>"); Bson command = new BsonDocument("ping", new BsonInt64(1)); Mono.from(database.runCommand(command)) .doOnSuccess(x -> System.out.println("Pinged your deployment. You successfully connected to MongoDB!")) .doOnError(err -> System.out.println("Error: " + err.getMessage())) .block(); } } }
ローカル配置
MongoDB のローカル配置に接続するには、ホスト名としてlocalhostを使用します。 デフォルトでは、 mongodプロセスはポート27017で実行されますが、これは配置に合わせてカスタマイズできます。
次のコードは、 Java Reactive Streams ドライバーを使用してローカルMongoDBデプロイに接続する方法を示しています。
import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoClient; public class MongoConnection { public static void main(String[] args) { String uri = "mongodb://localhost:27017/"; try (MongoClient client = MongoClients.create(uri)) { // use `client` here } } }
レプリカセット
レプリカセットに接続するには、IP 接続 でレプリカセットのホスト名(またはstring アドレス)とポート番号を指定します。
レプリカセットレプリカセットの 1 つ以上のホストを指定し、 Java Reactive Streams ドライバーに自動検出を実行して他のホストを検索するように指示できます。 ドライバーに自動検出を実行するように指示するには、次のいずれかのアクションを実行します。
replicaSetパラメーターの値としてレプリカセットの名前を指定します。directConnectionパラメーターの値としてfalseを指定します。レプリカセットに複数のホストを指定します。
次の例では、ドライバーはサンプル接続 URI を使用して、host1 を含む 3 つの異なるホストのポート 27017 で実行されている MongoDB レプリカセット sampleRS に接続します。
import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoClient; public class MongoConnection { public static void main(String[] args) { String uri = "mongodb://localhost:27017/?replicaSet=sampleRS"; try (MongoClient client = MongoClients.create(uri)) { // use `client` here } } }
注意
create() は非ブロッキング
MongoClientを構築するcreate()メソッドは非ブロッキングです。 レプリカセットに接続すると、クライアントがバックグラウンド スレッドを使用してレプリカセットに接続している間に、 メソッドはすぐに返します。
MongoClientを作成し、そのnodes属性の string 表現をすぐに出力すると、クライアントがレプリカセット メンバーに接続している間はリストが空になることがあります。
初期化
レプリカセットを初期化するには、単一のノードに直接接続する必要があります。 そのためには、 directConnection接続オプションをTrueに設定します。 これは、次の方法で行うことができます。
create()メソッドに引数を渡してMongoClient接続stringの パラメーターを設定します。
import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoClient; public class MongoConnection { public static void main(String[] args) { try (MongoClient client = MongoClients.create("mongodb://<hostname>:<port>", directConnection=True)){ // use `client` here } } }
import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoClient; public class MongoConnection { public static void main(String[] args) { String uri = "mongodb://<hostname>:<port>/?directConnection=true"; try (MongoClient client = MongoClients.create(uri)){ // use `client` here } } }
注意
Docker のレプリカセット
レプリカセットがDockerで実行される場合、公開されるMongoDBエンドポイントは 1 つだけです。この場合、レプリカセットは検出できません。接続 URI で directConnection=false を指定するか、このオプションを未設定のままにすると、アプリケーションがその接続に接続できなくなる可能性があります。
テスト環境または開発環境では、directConnection=true を指定してレプリカセットに接続できます。本番環境では、Docker 仮想ネットワークの外部から各 MongoDB インスタンスにアクセスできるようにクラスターを構成することを推奨します。
API ドキュメント
Java Reactive Streams ドライバーでMongoClientインスタンスを作成する方法について詳しくは、次のAPIドキュメントを参照してください。