Database Manual / Reference / Query Language / Update / Fields

$setOnInsert (update operator)(更新运算符)

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. Fields with numeric names are processed in numeric order. See Update Operators Behavior for details.从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 ( { } ). 从MongoDB 5.0开始,当您使用带有空操作数表达式({ })的更新运算符(如$setOnInsert)时,mongod不再引发错误。An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).空更新不会导致任何更改,也不会创建oplog条目(这意味着该操作是无操作)。

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 <query> to create a new document with _id: 1. $setOnInsert updates the document as specified.MongoDB使用<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参数为truedb.collection.updateOne()

  • creates a new document创建新文档
  • applies the $set operation应用$set操作
  • applies the $setOnInsert operation应用$setOnInsert操作

If db.collection.updateOne() matches an existing document, MongoDB only applies the $set operation.如果db.collection.updateOne()与现有文档匹配,MongoDB只应用$set操作。