db.collection.replaceOne()
MongoDB とドライバー
このページではmongosh
メソッドがドキュメントされています。 MongoDB ドライバーで同等のメソッドを確認するには、プログラミング言語の対応するページを参照してください。
定義
db.collection.replaceOne(filter, replacement, options)
Replaces a single document within the collection based on the filter.
次の値を返します。 次の要素を含むドキュメント: 操作が書き込み保証
付きで実行された場合はブール値
acknowledged
(true
)、書き込み保証が無効になっている場合はfalse
になります一致したドキュメントの数を含む
matchedCount
変更されたドキュメントの数を含む
modifiedCount
アップサートされたドキュメントの
_id
を含むupsertedId
互換性
このメソッドは、次の環境でホストされている配置で使用できます。
MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです
注意
このコマンドは、すべての MongoDB Atlas クラスターでサポートされています。すべてのコマンドに対する Atlas のサポートについては、「サポートされていないコマンド」を参照してください。
MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン
MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン
構文
バージョン8.0で変更。
replaceOne()
メソッドの形式は次のとおりです。
db.collection.replaceOne( <filter>, <replacement>, { upsert: <boolean>, writeConcern: <document>, collation: <document>, hint: <document|string>, sort: <document> } )
replaceOne()
メソッドは次のパラメーターを取ります。
Parameter | タイプ | 説明 | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
ドキュメント | ||||||||||||
| ドキュメント | The replacement document. Cannot contain update operators. | ||||||||||
| ブール値 | 任意。
MongoDB will add the 複数のアップサートを回避するため、 デフォルトは | ||||||||||
| ドキュメント | 任意。書込み保証(write concern)を表現するドキュメント。デフォルトの書込み保証を使用する場合は省略します。 トランザクションで実行される場合、操作の書込み保証 (write concern)を明示的に設定しないでください。トランザクションで書込み保証を使用するには、「トランザクション書込み保証」を参照してください。 | ||||||||||
| ドキュメント | 任意。 操作に使用する照合を指定します。 照合を指定すると、大文字・小文字やアクセント記号など、文字列を比較するための言語独自のルールを指定できます。 照合オプションの構文は次のとおりです。
照合を指定する場合、 照合が指定されていなくても、コレクションにデフォルトの照合が設定されている場合( コレクションにも操作にも照合が指定されていない場合、MongoDB では以前のバージョンで使用されていた単純なバイナリ比較によって文字列が比較されます。 1 つの操作に複数の照合は指定できません。たとえば、フィールドごとに異なる照合を指定できません。また、ソートと検索を一度に実行する場合、検索とソートで別の照合を使用できません。 | ||||||||||
ドキュメント | Optional. A document or string that specifies the index to use to support the フィルター. このオプションには、インデックス仕様ドキュメントまたはインデックス名の文字列を指定できます。 存在しないインデックスを指定した場合、操作はエラーになります。 For an example, see Specify | |||||||||||
| ドキュメント | 任意。 更新が適用される前にドキュメントを並べ替えます。 ソート引数がドキュメントでない場合、操作はエラーになります。 MongoDB では、コレクション内のドキュメントを特定の順序で保存することはありません。重複する値を含むフィールドでソートする場合、それらの値を含むドキュメントは任意の順序で返されます。 一貫したソート順序が必要な場合は、一意の値を含むフィールドを少なくとも 1 つ含めてソートしてください。これを保証する最も簡単な方法は、 詳細については、「ソートの整合性」を参照してください。 バージョン8.0の新機能。 For an example, see Replace One Document and Use a Sort. |
動作
replaceOne()
replaces the first matching document in
the collection that matches the filter
, using the replacement
document.
upsert
If upsert: true
and no documents match the filter
,
db.collection.replaceOne()
creates a new document based on
the replacement
document.
If you specify upsert: true
on a sharded collection, you must
include the full shard key in the filter
. For additional
db.collection.replaceOne()
behavior on a sharded collection,
see シャーディングされたコレクション.
上限付きコレクション
If a replacement operation changes the document size, the operation will fail.
時系列コレクション
You cannot use the replaceOne()
method on a
時系列コレクション.
シャーディングされたコレクション
db.collection.replaceOne()
attempts to target a single shard, first by
using the query filter. If the operation cannot target a single shard by the
query filter, it then attempts to target by the replacement document.
以前のバージョンでは、この操作では置換ドキュメントを使用するターゲットを試行します。
Shard Key Requirements In Replacement Document
The replacement document does not need to include the shard key.
警告
シャーディングされたコレクション内のドキュメントには、シャード キー フィールドがないことがあります。ドキュメントのシャード キーの値を変更するときに、誤ってシャード キーを削除しないように注意してください。
upsert
シャーディングされたコレクション
A db.collection.replaceOne()
operation that includes upsert: true
on a sharded collection must include the full shard key in the filter
.
ただし、シャーディングされたコレクション内のドキュメントにはシャードキー フィールドがない場合があります。シャードキーがないドキュメントを対象とするには、null
の等価一致を別のフィルター条件(_id
フィールド上と同様に)と組み合わせて使用できます。例え:
{ _id: <value>, <shardkeyfield>: null } // _id of the document missing shard key
シャードキーの変更
シャードキー フィールドが不変の _id
フィールドでない限り、ドキュメントのシャードキー値を更新できます。
警告
シャーディングされたコレクション内のドキュメントには、シャード キー フィールドがないことがあります。ドキュメントのシャード キーの値を変更するときに、誤ってシャード キーを削除しないように注意してください。
既存のシャードキー値をdb.collection.replaceOne()
で変更するには
必ず
mongos
上で使用します。シャードに直接操作を実行しないでください。トランザクション内で、または 再試行可能な書き込みとして実行する必要があります。
完全なシャードキーに等価 フィルター を含める 必要 があります 。
欠落しているシャードキー
シャーディングされたコレクション内のドキュメントには、シャードキー フィールドがない場合があります。db.collection.replaceOne()
を使用してドキュメントの欠落しているシャードキーを設定するには、mongos
で実行する必要があります。シャードに対して直接操作を実行しないでください。
さらに、次の要件も適用されます。
タスク | 要件 |
---|---|
|
|
|
|
Tip
欠落しているキー値は NULL 等価一致の一部として返されるため、NULL 値のキーが更新されないように、必要に応じて追加のクエリ条件(_id
フィールドなど)を追加します。
以下も参照してください。
トランザクション
db.collection.replaceOne()
は分散トランザクション内で使用できます。
重要
ほとんどの場合、分散トランザクションでは 1 つのドキュメントの書き込み (write) よりもパフォーマンス コストが高くなります。分散トランザクションの可用性は、効果的なスキーマ設計の代わりにはなりません。多くのシナリオにおいて、非正規化されたデータモデル(埋め込みドキュメントと配列)が引き続きデータやユースケースに最適です。つまり、多くのシナリオにおいて、データを適切にモデリングすることで、分散トランザクションの必要性を最小限に抑えることができます。
トランザクションの使用に関するその他の考慮事項(ランタイム制限や oplog サイズ制限など)については、「本番環境での考慮事項」も参照してください。
トランザクション内のアップサート
トランザクションがクロスシャード間書き込みトランザクション(write transaction)でない場合に、分散トランザクション内にコレクションとインデックスを作成できます。
db.collection.replaceOne()
と upsert: true
は、既存のコレクションまたは存在しないコレクションで実行できます。存在しないコレクションに対して実行すると、操作によってコレクションが作成されます。
以下も参照してください。
書込み保証とトランザクション
トランザクションで実行される場合、操作の書込み保証 (write concern)を明示的に設定しないでください。トランザクションで書込み保証を使用するには、「トランザクション書込み保証」を参照してください。
例
置換
restaurant
コレクションには次のドキュメントが含まれます:
{ "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan" }, { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 }, { "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 }
The following operation replaces a single document where
name: "Central Perk Cafe"
:
try { db.restaurant.replaceOne( { "name" : "Central Perk Cafe" }, { "name" : "Central Pork Cafe", "Borough" : "Manhattan" } ); } catch (e){ print(e); }
この操作では以下が返されます。
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
一致するものが見つからなかった場合、以下の結果が返されます。
{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }
設定 upsert: true
would insert the document if no match was found. See
Replace with Upsert
Replace with Upsert
restaurant
コレクションには次のドキュメントが含まれます。
{ "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan", "violations" : 3 }, { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 }, { "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 }
The following operation attempts to replace the document with
name : "Pizza Rat's Pizzaria"
, with upsert : true
:
try { db.restaurant.replaceOne( { "name" : "Pizza Rat's Pizzaria" }, { "_id": 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 8 }, { upsert: true } ); } catch (e){ print(e); }
Since upsert : true
the document is inserted based on the
replacement
document. The operation returns:
{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0, "upsertedId" : 4 }
コレクションには、次のドキュメントが含まれています。
{ "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan", "violations" : 3 }, { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 }, { "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 }, { "_id" : 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 8 }
Replace with Write Concern
3つのノードから成るレプリカセットにおいて、次の操作は w
の majority
と wtimeout
の 100
を指定します。
try { db.restaurant.replaceOne( { "name" : "Pizza Rat's Pizzaria" }, { "name" : "Pizza Rat's Pub", "Borough" : "Manhattan", "violations" : 3 }, { w: "majority", wtimeout: 100 } ); } catch (e) { print(e); }
承認に wtimeout
制限時間を超える時間がかかると、次の例外が発生します。
WriteConcernError({ "code" : 64, "errmsg" : "waiting for replication timed out", "errInfo" : { "wtimeout" : true, "writeConcern" : { "w" : "majority", "wtimeout" : 100, "provenance" : "getLastErrorDefaults" } } })
次の表は、errInfo.writeConcern.provenance
の値について説明したものです。
出所 | 説明 |
---|---|
| 書き込み保証(write concern)がアプリケーションで指定されました。 |
| 書込み保証 (write concern) は、カスタム定義されたデフォルト値に基づきます。 |
| 書込み保証 (write concern) は、レプリカセットの |
| 他の書き込み保証(write concern)が一切指定されていない状態で、サーバーから発生した書き込み保証。 |
照合の指定
照合を指定すると、大文字・小文字やアクセント記号など、文字列を比較するための言語独自のルールを指定できます。
コレクション myColl
は、次のドキュメントを含みます。
{ _id: 1, category: "café", status: "A" } { _id: 2, category: "cafe", status: "a" } { _id: 3, category: "cafE", status: "a" }
次の操作には照合オプションが含まれます。
db.myColl.replaceOne( { category: "cafe", status: "a" }, { category: "cafÉ", status: "Replaced" }, { collation: { locale: "fr", strength: 1 } } );
Specify hint
for replaceOne
次のドキュメントを使用してサンプルmembers
コレクションを作成します。
db.members.insertMany([ { "_id" : 1, "member" : "abc123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null }, { "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }, { "_id" : 3, "member" : "lmn123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null }, { "_id" : 4, "member" : "pqr123", "status" : "D", "points" : 20, "misc1" : "Deactivated", "misc2" : null }, { "_id" : 5, "member" : "ijk123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null }, { "_id" : 6, "member" : "cde123", "status" : "A", "points" : 86, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" } ])
コレクションに次のインデックスを作成します。
db.members.createIndex( { status: 1 } ) db.members.createIndex( { points: 1 } )
次の更新操作は、インデックス{
status: 1 }
を使用することを明示的に示しています。
注意
存在しないインデックスを指定した場合、操作はエラーになります。
db.members.replaceOne( { "points": { $lte: 20 }, "status": "P" }, { "misc1": "using index on status", status: "P", member: "replacement", points: "20"}, { hint: { status: 1 } } )
この操作では、以下を返します。
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
使用されているインデックスを表示するには、$indexStats
パイプラインを使用できます。
db.members.aggregate( [ { $indexStats: { } }, { $sort: { name: 1 } } ] )
Replace One Document and Use a Sort
次の restaurantsSort
コレクションを作成します。
db.restaurantsSort.insertMany( [ { _id: 1, name: "Pizza Place", rating: 4, violations: 2 }, { _id: 2, name: "Burger Joint", rating: 3, violations: 5 }, { _id: 3, name: "Taco Shop", rating: 4, violations: 1 } ] )
次の例では、"Pizza Place"
を "Clean Eats"
に置き換えます。
db.restaurantsSort.replaceOne( // Find restaurants with a rating of 4 { rating: 4 }, // Replace the found restaurant with Clean Eats { name: "Clean Eats", rating: 4, violations: 2 }, // Sort restaurants found by the most violations with a descending sort { sort: { violations: -1 } } )
例:
rating
が4
であるレストランを検索し、それらは"Pizza Place"
と"Taco Shop"
です。見つかったレストランを
violations
で降順に並べ替えます。これにより、最初の位置に"Pizza Place"
が配置されます。"Pizza Place"
を"Clean Eats"
に置き換えます。
次のクエリはレストランを返します。
db.restaurantsSort.find()
出力は、"Pizza Place"
が"Clean Eats"
に置き換えられたことを示しています:
[ { _id: 1, name: 'Clean Eats', rating: 4, violations: 2 }, { _id: 2, name: 'Burger Joint', rating: 3, violations: 5 }, { _id: 3, name: 'Taco Shop', rating: 4, violations: 1 } ]