ドキュメントの挿入
Overview
このガイドでは、 Scalaドライバーを使用して 挿入操作 を実行し、 MongoDBコレクションにドキュメントを追加する方法を学習できます。
挿入操作は 、1 つ以上の ドキュメント をMongoDBコレクションに挿入します。 次の方法を使用して、挿入操作を実行できます。
insertOne()
: 単一のドキュメントを挿入するinsertMany()
: 1 つ以上のドキュメントを挿入する
サンプル データ
このガイドの例では、restaurants
sample_restaurants
Atlasサンプルデータセット の データベースの コレクションを使用します。 Scalaアプリケーションからこのコレクションにアクセスするには、AtlasMongoClient
クラスターに接続する を作成し、 変数と 変数に次の値を割り当てます。database
collection
val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants") val collection: MongoCollection[Document] = database.getCollection("restaurants")
MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイドを参照してください。
_id フィールド
MongoDB コレクションでは、各ドキュメントに一意のフィールド値を持つ_id
フィールドが含まれている必要があります。
MongoDB では、このフィールドは次の 2 つの方法で管理できます。
各ドキュメントの
_id
フィールドを自分で設定し、各値が一意であることを確認します。ドライバーがドキュメント
_id
フィールドごとに一意のBsonObjectId
値を自動的に生成できるようにします。
一意性を保証できない限り、ドライバーに_id
値を自動的に生成させることをお勧めします。
注意
重複した _id
値はユニークインデックス制約に違反するため、ドライバーはエラーを返します。
_id
フィールドの詳細については、 マニュアルの 「 一意なインデックス 」MongoDB Server のガイドを参照してください。
ドキュメント構造とルールの詳細については、MongoDB Server マニュアルのドキュメントガイド を参照してください。
1つのドキュメントの挿入
MongoDBコレクションに単一のドキュメントを追加するには、insertOne()
メソッドを呼び出し、挿入するドキュメントを渡します。
次の例では、 restaurants
コレクションにドキュメントを挿入します。
val doc: Document = Document("name" -> "Neighborhood Bar & Grill", "borough" -> "Queens") val observable: Observable[InsertOneResult] = collection.insertOne(doc) observable.subscribe(new Observer[InsertOneResult] { override def onNext(result: InsertOneResult): Unit = println(result) override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage) override def onComplete(): Unit = println("Completed") })
AcknowledgedInsertOneResult{insertedId=BsonObjectId{value=...}} Completed
複数のドキュメントの挿入
MongoDBコレクションに複数のドキュメントを追加するには 、insertMany()
関数を呼び出し、挿入するドキュメントのリストを渡します。
次の例では、 restaurants
コレクションに 2 つのドキュメントを挿入しています。
val docs: Seq[Document] = Seq( Document("name" -> "Metropolitan Cafe", "borough" -> "Queens"), Document("name" -> "Yankee Bistro", "borough" -> "Bronx") ) val observable: Observable[InsertManyResult] = collection.insertMany(docs) observable.subscribe(new Observer[InsertManyResult] { override def onNext(result: InsertManyResult): Unit = println(result) override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage) override def onComplete(): Unit = println("Completed") })
AcknowledgedInsertManyResult{insertedIds={0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}}} Completed
挿入動作の変更
insertOne()
メソッドはオプションで、挿入操作を構成するためのオプションを設定するInsertOneOptions
パラメーターを受け入れます。 オプションを指定しない場合、ドライバーはデフォルト設定で挿入操作を実行します。 最後のパラメータとしてオプションをinsertOne()
メソッドに渡します。
次の表では、 InsertOneOptions
インスタンスを構成するために使用できる setter メソッドについて説明します。
方式 | 説明 |
---|---|
| If set to true , allows the driver to ignore
document-level validation.Defaults to false . |
| Sets a comment to attach to the operation. For more information, see the insert command
fields guide in the
MongoDB Server manual for more information. |
InsertManyOptions
インスタンスを構成することで、insertMany()
メソッドで上記の設定を設定できます。また、ordered()
設定メソッドを使用して、ドライバーがMongoDBにドキュメントを挿入する順序を指定することもできます。最後のパラメータとしてオプションを insertMany()
メソッドに渡します。
例
次のコードでは、insertMany()
メソッドを使用して、3 つの新しいドキュメントをコレクションに挿入します。 bypassDocumentValidation
オプションが有効になっているため、この挿入操作はドキュメントレベルの検証をバイパスします。
val docs: Seq[Document] = Seq( Document("name" -> "One Night's Delight", "borough" -> "Queens"), Document("name" -> "Second Street Pub", "borough" -> "Manhattan"), Document("name" -> "Triple Crown Diner", "borough" -> "Brooklyn") ) val opts: InsertManyOptions = InsertManyOptions().bypassDocumentValidation(true) val observable: Observable[InsertManyResult] = collection.insertMany(docs, opts) observable.subscribe(new Observer[InsertManyResult] { override def onNext(result: InsertManyResult): Unit = println(result) override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage) override def onComplete(): Unit = println("Completed") })
AcknowledgedInsertManyResult{insertedIds={0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}, 2=BsonObjectId{value=...}}} Completed
詳細情報
このガイドで説明されているメソッドの詳細については、次の API ドキュメントを参照してください。