定义
$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操作。