정의
$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부터 업데이트 연산자는 문자열 기반 이름이 있는 문서 필드를 사전순으로 처리합니다. 숫자 이름이 있는 필드는 숫자 순서대로 처리됩니다. 자세한 내용은 업데이트 운영자 동작을 참조하십시오.
MongoDB 부터 5.0 mongod 빈 $setOnInsert 피연산자 표현식 ( { } )과 함께 와 같은 업데이트 연산자 사용할 때 에서 더 이상 오류가 발생하지 않습니다. 빈 업데이트 는 변경 사항이 없으며 oplog 항목이 생성되지 않습니다(즉, 작업이 작동하지 않음을 의미합니다).
예시
products collection에 문서가 없습니다.
upsert:true 매개변수인 db.collection.updateOne()를 사용하여 새 문서를 삽입합니다.
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 collection에 새로 삽입된 문서가 포함되어 있습니다.
{ "_id" : 1, "item" : "apple", "defaultQty" : 100 }
upsert 매개 변수가 true 인 경우db.collection.updateOne():
새 문서를 생성합니다.
$set연산을 적용합니다.applies the
$setOnInsertoperation
db.collection.updateOne()가 기존 문서와 일치하는 경우 MongoDB는 작업만 $set 적용합니다.