Overview
このガイドでは、 MongoDB PHPライブラリを使用してMongoDBコレクション内のドキュメントを更新する方法を学習できます。 単一のドキュメントを更新するには MongoDB\Collection::updateOne()
メソッドを呼び出し、複数のドキュメントを更新するにはMongoDB\Collection::updateMany()
メソッドを呼び出します。
サンプル データ
このガイドの例では、 Atlasサンプルデータセットのsample_restaurants
データベースのrestaurants
コレクションを使用します。 PHPアプリケーションからこのコレクションにアクセスするには、Atlas クラスターに接続するMongoDB\Client
をインスタンス化し、 $collection
変数に次の値を割り当てます。
$collection = $client->sample_restaurants->restaurants;
MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイドを参照してください。
アップデート操作
MongoDB では、次の方法で更新操作を実行できます。
MongoDB\Collection::updateOne()
は、検索条件に一致する最初のドキュメントを更新します。MongoDB\Collection::updateMany()
は、検索条件に一致するすべてのドキュメントを更新します
各更新方法には次のパラメーターが必要です。
クエリフィルタードキュメント: 更新するドキュメントを指定します。 クエリフィルターの詳細については、 MongoDB Serverマニュアルの「クエリフィルター ドキュメント 」セクションを参照してください。
ドキュメントの更新:更新演算子、または実行する更新の種類と、変更するフィールドと値を指定します。 更新演算子とその使用方法のリストについては、 MongoDB Serverマニュアルの「フィールド更新演算子 」のガイドを参照してください。
1 つのドキュメントの更新
次の例では、 updateOne()
メソッドを使用して、 restaurants
コレクション内のドキュメントのname
値を'Bagels N Buns'
から'2 Bagels 2 Buns'
に更新します。
$result = $collection->updateOne( ['name' => 'Bagels N Buns'], ['$set' => ['name' => '2 Bagels 2 Buns']], );
多くのドキュメントの更新
次の例では、 updateMany()
メソッドを使用して、 cuisine
の値が'Pizza'
であるすべてのドキュメントを更新します。 更新後、ドキュメントのcuisine
値は'Pasta'
になります。
$result = $collection->updateMany( ['cuisine' => 'Pizza'], ['$set' => ['cuisine' => 'Pasta']], );
更新操作をカスタマイズする
オプション値を指定する配列をパラメーターとして渡すことで、 updateOne()
メソッドとupdateMany()
メソッドの動作を変更できます。 次の表では、 配列に設定できるオプションの一部を説明しています。
オプション | 説明 |
---|---|
| 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 . |
| 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 . |
| Applies to updateOne() only. Specifies the sort order to
apply to documents before performing the update operation. |
| Specifies the kind of language collation to use when sorting
results. To learn more, see the Collation section
of this page. |
| Specifies which array elements an update applies to if the operation modifies
array fields. |
| Sets the index to scan for documents.
For more information, see the hint statement
in the MongoDB Server manual. |
| Sets the write concern for the operation.
For more information, see Write Concern
in the MongoDB Server manual. |
| Specifies a document with a list of values to improve operation readability.
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. |
| A comment to attach to the operation. For more information, see the insert command
fields guide in the
MongoDB Server manual. |
次の例では、 updateMany()
メソッドを使用して、 borough
の値が'Manhattan'
であるすべてのドキュメントを検索します。 次に、これらのドキュメントのborough
値を'Manhattan (north)'
にアップデートします。 upsert
オプションがtrue
に設定されているため、クエリフィルターが既存のドキュメントと一致しない場合、 MongoDB PHPライブラリは新しいドキュメントを挿入します。
$result = $collection->updateMany( ['borough' => 'Manhattan'], ['$set' => ['borough' => 'Manhattan (north)']], ['upsert' => true], );
照合
操作の 照合 を指定するには、collation
オプションを設定する $options
配列パラメータを操作メソッドに渡します。照合ルールを構成する配列に collation
オプションを割り当てます。
次の表では、照合を構成するために設定できるフィールドについて説明しています。
フィールド | 説明 |
---|---|
| (Required) Specifies the International Components for Unicode (ICU) locale. For a
list of supported locales, see Collation Locales and Default Parameters
in the MongoDB Server manual. Data Type: string |
| (Optional) Specifies whether to include case comparison. When set to true , the comparison behavior depends on the value of
the strength field:- If strength is 1 , the PHP library compares basecharacters and case. - If strength is 2 , the PHP library compares basecharacters, diacritics, other secondary differences, and case. - If strength is any other value, this field is ignored.When set to false , the PHP library doesn't include case comparison at
strength level 1 or 2 .Data Type: bool Default: false |
| (Optional) Specifies the sort order of case differences during tertiary
level comparisons. Data Type: string Default: "off" |
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. Data Type: int Default: 3 |
| (Optional) Specifies whether the driver compares numeric strings as numbers. If set to true , the PHP library compares numeric strings as numbers.
For example, when comparing the strings "10" and "2", the library uses the
strings' numeric values and treats "10" as greater than "2".If set to false , the PHP library compares numeric strings
as strings. For example, when comparing the strings "10" and "2", the library
compares one character at a time and treats "10" as less than "2".For more information, see Collation Restrictions
in the MongoDB Server manual. Data Type: bool Default: false |
| (Optional) Specifies whether the library considers whitespace and punctuation as base
characters for comparison purposes. Data Type: string Default: "non-ignorable" |
| (Optional) Specifies which characters the library considers ignorable when
the alternate field is set to "shifted" .Data Type: string Default: "punct" |
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: bool Default: false |
照合と各フィールドに可能な値の詳細については、 MongoDB Serverマニュアルの「 照合 」エントリを参照してください。
戻り値
updateOne()
メソッドとupdateMany()
メソッドはMongoDB\UpdateResult
クラスのインスタンスを返します。 このクラスには、次のメンバー関数が含まれています。
関数 | 説明 |
---|---|
| Returns the number of documents that matched the query filter, regardless of
how many were updated. |
| Returns the number of documents modified by the update operation. If an updated
document is identical to the original, it is not included in this
count. |
| Returns a boolean indicating whether the server acknowledged
the write operation. |
| Returns the number of document that were upserted into the database. |
| Returns the ID of the document that was upserted in the database, if the driver
performed an upsert. |
次の例では、 updateMany()
メソッドを使用して、一致するドキュメントのname
フィールドを'Dunkin' Donuts'
から'Dunkin''
にアップデートします。 変更されたドキュメントの数を出力するには、 getModifiedCount()
メンバー関数を呼び出します。
$result = $collection->updateMany( ['name' => 'Dunkin\' Donuts'], ['$set' => ['name' => 'Dunkin\'']], ); echo 'Modified documents: ', $result->getModifiedCount();
Modified documents: 206
詳細情報
クエリフィルターの作成の詳細については、「クエリの指定」ガイドを参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。