On this page本页内容
$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. upsert:true
的更新操作导致插入文档,则$setOnInsert
将指定值分配给文档中的字段。If the update operation does not result in an insert, 如果更新操作没有导致插入,$setOnInsert
does nothing.$setOnInsert
不执行任何操作。
You can specify the 您可以为以下项指定upsert
option for:upsert
选项:
db.collection.updateOne( <query>, { $setOnInsert: { <field1>: <value1>, ... } }, { upsert: true } )
To specify a 要在嵌入文档或数组中指定<field>
in an embedded document or in an array, use dot notation.<field>
,请使用点表示法。
Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. 从MongoDB 5.0开始,更新运算符以词典顺序处理具有基于字符串的名称的文档字段。Fields with numeric names are processed in numeric order. 具有数字名称的字段按数字顺序处理。See Update Operators Behavior for details.有关详细信息,请参阅更新运算符行为。
Starting in MongoDB 5.0, 从MongoDB 5.0开始,当使用带有空操作数表达式({})的更新运算符(如mongod
no longer raises an error when you use an update operator like $setOnInsert
with an empty operand expression ( { }
). $setOnInsert
)时,mongod
不再引发错误。An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).空更新不会导致任何更改,也不会创建oplog条目(这意味着该操作是无操作)。
The products
collection contains no documents.products
集合不包含任何文档。
Insert a new document using 使用db.collection.updateOne()
the upsert: true parameter.db.collection.updateOne()
和upsert:true
参数插入新文档。
db.products.updateOne( { _id: 1 }, { $set: { item: "apple" }, $setOnInsert: { defaultQty: 100 } }, { upsert: true } )
MongoDB uses MongoDB使用<query>
to create a new document with _id: 1
. <query>
创建一个_id:1
的新文档。$setOnInsert
updates the document as specified.按指定更新文档。
The products
collection contains the newly-inserted document:products
集合包含新插入的文档:
{ "_id" : 1, "item" : "apple", "defaultQty" : 100 }
When the upsert parameter is 当true
db.collection.updateOne()
:upsert
参数为true
时,db.collection.updateOne()
:
$set
operation$set
操作$setOnInsert
operation$setOnInsert
操作If 如果db.collection.updateOne()
matches an existing document, MongoDB only applies the $set
operation.db.collection.updateOne()
与现有文档匹配,MongoDB只应用$set
操作。