$setOnInsert
On this page本页内容
Definition定义
$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>
,请使用点表示法。
Behavior行为
Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. 从MongoDB 5.0开始,update运算符按照字典顺序处理具有基于字符串的名称的文档字段。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).空更新不会导致任何更改,也不会创建操作日志条目(这意味着该操作是无操作)。
Example实例
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
. $setOnInsert
updates the document as specified.<query>
创建一个_id
为1
的新文档。$setOnInsert
根据指定更新文档。
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()
:
creates a new document创建新文档applies the应用$set
operation$set
操作applies the应用$setOnInsert
operation$set
操作
If 如果db.collection.updateOne()
matches an existing document, MongoDB only applies the $set
operation.db.collection.updateOne()
与现有文档匹配,MongoDB只应用$set
操作。