定義
$setOnInsertIf an update operation with upsert: true results in an insert of a document, then
$setOnInsertassigns the specified values to the fields in the document. If the update operation does not result in an insert,$setOnInsertdoes 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
$setOnInsertoperation
db.collection.updateOne() が既存のドキュメントと一致する場合、MongoDB は$set 操作のみを適用します。