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

Update Documents

このガイドでは、 Kotlin Sync ドライバーを使用して MongoDBupdateOne() updateMany()コレクション内のドキュメントを更新する方法を学習できます。これには メソッドと メソッドが使用されます。

The examples in this guide use the sample_restaurants.restaurants collection from the Atlas sample datasets. To learn how to create a free MongoDB deployment and load the sample datasets, see the MongoDB Get Started guide.

このコレクション内のドキュメントは、次の Kotlin データ クラスによってモデル化されます。

data class Restaurant(
val name: String,
val borough: String,
val cuisine: String,
val address: Document
)

次の方法を使用して、MongoDB 内のドキュメントを更新できます。

  • updateOne()は、検索条件に一致する最初のドキュメントを更新します。

  • updateMany()は、検索条件に一致するすべてのドキュメントを更新します

各更新方法には次のパラメーターが必要です。

  • クエリフィルター。アップデートするドキュメントに一致する。 クエリフィルターの詳細については、「クエリの指定」ガイドを参照してください。

  • 更新ドキュメント。更新演算子または実行する更新の種類と、更新されるフィールドと値を指定します。 更新演算子とその使用方法のリストについては、 MongoDB Serverマニュアルの「 フィールド更新演算子 」のガイド ページ を参照してください。

次の例では、 updateOne()メソッドを使用して、ドキュメントのnameの値を"Happy Garden"から"Mountain House"に更新します。

val filter = eq(Restaurant::name.name, "Happy Garden")
val update = set(Restaurant::name.name, "Mountain House")
val result = collection.updateOne(filter, update)

次の例では、 updateMany()メソッドを使用して、 nameの値が"Starbucks"であるすべてのドキュメントを更新します。 アップデートにより、 addressフィールドの名前がlocationに変更されます。

val filter = eq(Restaurant::name.name, "Starbucks")
val update = rename(Restaurant::address.name, "location")
val result = collection.updateMany(filter, update)

updateOne()メソッドとupdateMany()メソッドは、更新操作を構成するためのオプションを設定する パラメーターをオプションで受け入れます。 オプションを指定しない場合、ドライバーはデフォルト設定で更新操作を実行します。

次の表では、 UpdateOptionsインスタンスを構成するために使用できる setter メソッドについて説明します。

プロパティ
説明

upsert()

Specifies whether the update operation performs an upsert operation if no documents match the query filter. For more information, see the upsert statement in the MongoDB Server manual.
Defaults to false

sort(Bson sort)

操作に適用するソート基準を設定します。 updateOne() メソッドに渡すクエリフィルターに複数のドキュメントが一致する場合、この操作最初の結果が更新されます。 このオプションを に設定すると、一致したドキュメントに順序を適用し、更新されるドキュメントをより詳細に制御できます。

bypassDocumentValidation()

Specifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual.
Defaults to false.

collation()

Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.

arrayFilters()

アップデートを適用する配列要素を選択するために指定するフィルターのリストを提供します。

hint()

Sets the index to use when matching documents. For more information, see the hint statement in the MongoDB Server manual.

let()

Provides a map of parameter names and values to set top-level variables for the operation. Values must be constant or closed expressions that don't reference document fields. For more information, see the let statement in the MongoDB Server manual.

comment()

Sets a comment to attach to the operation. For more information, see the update command fields guide in the MongoDB Server manual for more information.

次のコードでは、 updateOne()メソッドを使用して、 nameフィールドの値が"Sunrise Pizzeria"であるドキュメントを一致させます。 次に、最初に一致するドキュメントのboroughの値を"Queens"に、 cuisineの値を"Italian"に設定します。

upsertオプションがtrueに設定されているため、クエリフィルターが既存のドキュメントと一致しない場合、ドライバーはアップデート ドキュメントで指定されたフィールドと値を含む新しいドキュメントを挿入します。

val opts = UpdateOptions().upsert(true)
val filter = eq(Restaurant::name.name, "Sunrise Pizzeria")
val update = combine(
set(Restaurant::borough.name, "Queens"),
set(Restaurant::cuisine.name, "Italian")
)
collection.updateOne(filter, update, opts)

updateOne()メソッドとupdateMany()メソッドはそれぞれUpdateResultオブジェクトを返します。 UpdateResultインスタンスからの情報にアクセスするには、次のメソッドを使用できます。

プロパティ
説明

getMatchedCount()

アップデートが実行された回数に関係なく、クエリフィルターに一致したドキュメントの数を返します。

getModifiedCount()

更新操作によって変更されたドキュメントの数を返します。 更新されたドキュメントが元と同一の場合、このカウントには含まれません。

wasAcknowledged()

サーバーが結果を確認した場合は true を返します。

getUpsertedId()

ドライバーがアップサートを実行した場合、データベースでアップサートされたドキュメントの _id 値を返します。

注意

wasAcknowledged()メソッドがfalseを返す場合、 UpdateResultインスタンスから他の情報にアクセスしようとすると、 InvalidOperation例外が発生します。 サーバーが書込み (write) 操作を確認しない場合、ドライバーはこれらの値を決定できません。

Kotlin Syncドライバーを使用してドキュメントを更新する方法を示す実行可能なコード例については、「 ドキュメントの挿入 」を参照してください。

このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。