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

$setOnInsert(更新演算子)

$setOnInsert

If an update operation with upsert: true results in an insert of a document, then $setOnInsert assigns the specified values to the fields in the document. If the update operation does not result in an insert, $setOnInsert does nothing.

次の upsert オプションを指定できます。

db.collection.updateOne(
<query>,
{ $setOnInsert: { <field1>: <value1>, ... } },
{ upsert: true }
)

<field> を埋め込みドキュメントまたは配列で指定するには、ドット表記を使用します。

MongoDB 5.0 以降、更新演算子では名前が文字列ベースのドキュメントフィールドを辞書順に処理します。数値名のフィールドは、数値順に処理されます。詳細については、「更新演算子の動作」を参照してください。

Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $setOnInsert with an empty operand expression ( { } ). An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).

products コレクションにはドキュメントが含まれていません。

db.collection.updateOne() upsert: true パラメーターを使用して新しいドキュメントを挿入します。

db.products.updateOne(
{ _id: 1 },
{
$set: { item: "apple" },
$setOnInsert: { defaultQty: 100 }
},
{ upsert: true }
)

MongoDB uses <query> to create a new document with _id: 1. $setOnInsert updates the document as specified.

products コレクションには新しく挿入されたドキュメントが含まれています:

{ "_id" : 1, "item" : "apple", "defaultQty" : 100 }

upsert パラメーターがtrue db.collection.updateOne()の場合:

  • が新しいドキュメントを作成します

  • が $set操作を適用します

  • applies the $setOnInsert operation

db.collection.updateOne() が既存のドキュメントと一致する場合、MongoDB は$set 操作のみを適用します。

このページを評価

項目一覧