ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs Menu

db.collection.replaceOne()

MongoDB とドライバー

このページではmongoshメソッドがドキュメントされています。 MongoDB ドライバーで同等のメソッドを確認するには、プログラミング言語の対応するページを参照してください。

db.collection.replaceOne(filter, replacement, options)

Replaces a single document within the collection based on the filter.

次の値を返します。次の要素を含むドキュメント:
  • 操作が書き込み保証付きで実行された場合はブール値acknowledgedtrue )、書き込み保証が無効になっている場合は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
タイプ
説明

ドキュメント

更新の選択基準。find()メソッドと同じクエリ セレクターを使用できます。

Specify an empty document { } to replace the first document returned in the collection.

replacement

ドキュメント

The replacement document.

Cannot contain update operators.

upsert

ブール値

任意。 trueの場合、replaceOne() は次のいずれかになります。

  • Inserts the document from the replacement parameter if no document matches the filter.

  • Replaces the document that matches the filter with the replacement document.

MongoDB will add the _id field to the replacement document if it is not specified in either the filter or replacement documents. If _id is present in both, the values must be equal.

複数のアップサートを回避するため、query フィールドにユニークインデックスが付けられていることを確認します。

デフォルトは false です。

writeConcern

ドキュメント

任意。書込み保証(write concern)を表現するドキュメント。デフォルトの書込み保証を使用する場合は省略します。

トランザクションで実行される場合、操作の書込み保証 (write concern)を明示的に設定しないでください。トランザクションで書込み保証を使用するには、「トランザクション書込み保証」を参照してください。

collation

ドキュメント

任意。

操作に使用する照合を指定します。

照合を指定すると、大文字・小文字やアクセント記号など、文字列を比較するための言語独自のルールを指定できます。

照合オプションの構文は次のとおりです。

collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}

照合を指定する場合、locale フィールドは必須ですが、その他の照合フィールドはすべて任意です。フィールドの説明については、照合ドキュメントを参照してください。

照合が指定されていなくても、コレクションにデフォルトの照合が設定されている場合(db.createCollection() を参照)には、コレクションの照合が使用されます。

コレクションにも操作にも照合が指定されていない場合、MongoDB では以前のバージョンで使用されていた単純なバイナリ比較によって文字列が比較されます。

1 つの操作に複数の照合は指定できません。たとえば、フィールドごとに異なる照合を指定できません。また、ソートと検索を一度に実行する場合、検索とソートで別の照合を使用できません。

ドキュメント

Optional. A document or string that specifies the index to use to support the フィルター.

このオプションには、インデックス仕様ドキュメントまたはインデックス名の文字列を指定できます。

存在しないインデックスを指定した場合、操作はエラーになります。

For an example, see Specify hint for replaceOne.

sort

ドキュメント

任意。

更新が適用される前にドキュメントを並べ替えます。

ソート引数がドキュメントでない場合、操作はエラーになります。

MongoDB では、コレクション内のドキュメントを特定の順序で保存することはありません。重複する値を含むフィールドでソートする場合、それらの値を含むドキュメントは任意の順序で返されます。

一貫したソート順序が必要な場合は、一意の値を含むフィールドを少なくとも 1 つ含めてソートしてください。これを保証する最も簡単な方法は、_idフィールドをソートのクエリに含めることです。

詳細については、「ソートの整合性」を参照してください。

バージョン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.

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 シャーディングされたコレクション.

See Replace with Upsert.

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.

以前のバージョンでは、この操作では置換ドキュメントを使用するターゲットを試行します。

The replacement document does not need to include the shard key.

警告

シャーディングされたコレクション内のドキュメントには、シャード キー フィールドがないことがあります。ドキュメントのシャード キーの値を変更するときに、誤ってシャード キーを削除しないように注意してください。

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()で変更するには

シャーディングされたコレクション内のドキュメントには、シャードキー フィールドがない場合がありますdb.collection.replaceOne()を使用してドキュメントの欠落しているシャードキーを設定するには、mongosで実行する必要があります。シャードに対して直接操作を実行しないでください

さらに、次の要件も適用されます。

タスク
要件

null に設定するには

  • upsert: trueが指定されている場合は、完全なシャードキーに等価フィルターが必要です。

null以外の値に設定するには

  • トランザクション 内で、または再試行可能な書き込みとして実行する必要があります

  • 次のいずれかの場合、完全なシャードキーに等価フィルターが必要です。

    • upsert: true 、または

    • the new shard key value belongs to a different shard.

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

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 }

3つのノードから成るレプリカセットにおいて、次の操作は wmajoritywtimeout100 を指定します。

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の値について説明したものです。

出所
説明

clientSupplied

書き込み保証(write concern)がアプリケーションで指定されました。

customDefault

書込み保証 (write concern) は、カスタム定義されたデフォルト値に基づきます。setDefaultRWConcern を参照してください。

getLastErrorDefaults

書込み保証 (write concern) は、レプリカセットの settings.getLastErrorDefaults のフィールドに基づきます。

implicitDefault

他の書き込み保証(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 } }
);

次のドキュメントを使用してサンプル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 } } ] )

次の 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 } }
)

例:

  • rating4であるレストランを検索し、それらは"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 }
]