MongoClient の作成
Overview
MongoDB 配置に接続するには、次の 2 つのものが必要です。
接続 URI (接続文字列とも呼ばれます)で、接続するMongoDBデプロイのScalaドライバーに指示します。
MongoClientオブジェクト。への接続を作成し、 MongoDBデプロイで操作を実行できるようにします。
MongoClientSettings
を使用して、 MongoDBに接続中のScalaドライバーの動作をカスタマイズすることもできます。
このガイドでは、接続stringを作成し、MongoClient
オブジェクトを使用してMongoDBに接続する方法について説明します。
接続URI
標準の接続stringには次のコンポーネントが含まれます。
コンポーネント | 説明 |
---|---|
| 必須: これを標準接続形式の文字列として識別するプレフィックス。 |
| |
| 必須。 MongoDB が実行されているホストとオプションのポート番号。 ポート番号を指定しない場合、ドライバーはデフォルトのポート |
| 任意。 接続stringに |
| 任意。接続固有のオプションを |
接続文字列の作成の詳細については、 MongoDB Serverマニュアルの「 接続文字列 」を参照してください。
Atlas 接続例
Atlas 上の MongoDB 配置に接続するには、まずクライアントを作成する必要があります。
接続 URI を string としてMongoClient.create()
メソッドに渡して、MongoDB インスタンスに接続できます。
// Replace the placeholder with your Atlas connection string val connectionString = "<connection string>" // Create a new client and connect to the server val mongoClient = MongoClient(connectionString) val database = mongoClient.getDatabase("sample_mflix")
また、MongoClientSettings
オブジェクトを MongoClient
オブジェクトに渡すことで、必要な構成を持つクライアントを作成することもできます。
MongoClientSettings
オブジェクト をインスタンス化するには、builder()
メソッドを呼び出し、applyConnectionString()
メソッドをチェーンして接続文字列を渡します。 また、 builder()
メソッドを使用して、他のクライアントオプションを指定することもできます。 必要な構成が完了したら、build()
メソッドを呼び出します。
新しいサーバー バージョンにアップグレードするときに重大な変更を回避するために、Stable API バージョンのクライアント オプションを設定できます。 Stable API 機能について詳しくは、「 Stable API 」ページをご覧ください。
次のコードは、Atlas 上の MongoDB 配置に接続するときに接続文字列と Stable API クライアント オプションを指定し、接続が成功したことを確認する方法を示します。
import com.mongodb.{ServerApi, ServerApiVersion} import org.mongodb.scala.{ConnectionString, MongoClient, MongoClientSettings} import org.mongodb.scala.bson.Document import scala.concurrent.Await import scala.concurrent.duration.DurationInt import scala.util.Using object MongoClientConnectionExample { def main(args: Array[String]): Unit = { // Replace the placeholder with your Atlas connection string val connectionString = "<connection string>" // Construct a ServerApi instance using the ServerApi.builder() method val serverApi = ServerApi.builder.version(ServerApiVersion.V1).build() val settings = MongoClientSettings .builder() .applyConnectionString(ConnectionString(connectionString)) .serverApi(serverApi) .build() // Create a new client and connect to the server Using(MongoClient(settings)) { mongoClient => // Send a ping to confirm a successful connection val database = mongoClient.getDatabase("admin") val ping = database.runCommand(Document("ping" -> 1)).head() Await.result(ping, 10.seconds) System.out.println("Pinged your deployment. You successfully connected to MongoDB!") } } }
API ドキュメント
Scalaドライバーを使用して MongoClient
オブジェクトを作成する方法の詳細については、次のAPIドキュメントを参照してください。