Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Ruby ドライバー
/

Update Documents

このガイドでは、 Rubyドライバーを使用して update_one メソッドと update_many メソッドを使用してMongoDBコレクション内のドキュメントを更新する方法を学習できます。

このガイドの例では、 Atlasサンプルデータセットsample_restaurantsデータベースの restaurantsコレクションを使用します。Rubyアプリケーションからこのコレクションにアクセスするには、Atlas クラスターに接続する Mongo::Clientオブジェクトを作成し、次の値を database 変数と collection 変数に割り当てます。

database = client.use('sample_restaurants')
collection = database[:restaurants]

MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイドを参照してください。

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

  • update_one: 検索条件に一致する最初のドキュメントを更新します

  • update_many: 検索条件に一致するすべてのドキュメントを更新します

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

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

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

次の例では、update_one メソッドを使用して、nameフィールドの値が "Happy Garden" である最初のドキュメントを検索します。次に、$set 演算子を使用して nameフィールドの値を "Mountain House" に更新します。

filter = { name: 'Happy Garden' }
update = { '$set' => { name: 'Mountain House' } }
single_result = collection.update_one(filter, update)
puts "#{single_result.modified_count} document(s) updated."
1 document(s) updated

次の例では、update_many メソッドを使用して、nameフィールドの値が "Starbucks" であるすべてのドキュメントを更新します。アップデートドキュメントでは、$rename 演算子を使用して、addressフィールドの名前を location に変更します。

filter = { name: 'Starbucks' }
update = { '$rename' => { address: 'location' } }
many_result = collection.update_many(filter, update)
puts "#{many_result.modified_count} document(s) updated."
11 document(s) updated

update_one メソッドと update_many メソッドは、 更新操作を構成するための オプションを受け入れます。これらのオプションをパラメーターとして個別に渡すことも、オプションを含む Hashオブジェクトを作成し、そのオブジェクトをパラメーターとして渡すこともできます。オプションを指定しない場合、ドライバーはデフォルト設定で更新操作を実行します。

次の表では、更新操作を構成するために使用できるオプションについて説明します。

オプション
説明

upsert

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.
Default: false

bypass_document_validation

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.
Default: false

collation

Language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.

array_filters

List of filters that you specify to select which array elements the update applies to.

hint

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

let

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.

この例では、$equal 演算子を使用して、nameフィールドの値が "Sunrise Pizzeria" であるドキュメントを一致させます。次に、$set 演算子を使用して、最初に一致するドキュメントの boroughフィールド値を "Queens" に設定し、cuisineフィールド値を "Italian" に設定します。

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

filter = { 'name' => 'Sunrise Pizzeria' }
update = { '$set' => { borough: 'Queens', cuisine: 'Italian' } }
upsert_result = collection.update_one(filter, update, upsert: true)
puts "#{upsert_result.modified_count} document(s) updated."
1 document(s) updated

update_one メソッドと update_many メソッドはそれぞれ Resultオブジェクトを返します。Resultインスタンスから次のメソッドにアクセスできます。

方式
説明

matched_count

Number of documents that matched the query filter, regardless of how many updates were performed.

modified_count

Number of documents modified by the update operation. If an updated document is identical to the original, it is not included in this count.

acknowledged?

Returns true if the server acknowledged the result.

upserted_count

Returns the number of documents that were upserted in the database, if the driver performed an upsert.

upserted_ids

Returns the _id value of the document that was upserted in the database, if the driver performed an upsert.

Tip

他の Result メソッドを呼び出す前に、acknowledged? メソッドの値を確認してください。acknowledged? メソッドが false を返す場合、Resultオブジェクトで他のメソッドを呼び出すと、ドライバーは InvalidOperation 例外をスローします。サーバーが書込み (write)操作を確認しない場合、ドライバーはこれらの値を決定できません。

Rubyドライバーを使用してドキュメントを更新する方法を示す実行可能なコード例については、 MongoDBへのデータの書込み を参照してください。

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

戻る

ドキュメントの置換

項目一覧